String to int, String to Integer

A common conversion is taking a string from a web request parameter or parse a CSV from storage and converting it to a primitive data type or a Integer object in java. Below we will show various ways to convert string type objects to primitive data type. On the flip side we also show how to convert an int back to a string because there could be an instance you wish to operate on the value as a string. Remember that a NumberFormatException will be thrown in the even that you attempt to convert a string to a numeric type but it doesn't have an appropriate format.

String to int

@Test
public void string_to_int() {

    String myString = "2";

    int variable = Integer.parseInt(myString);

    assertEquals(2, variable);
}

Int back to string

@Test
public void int_to_string() {

    int number = 2;

    assertEquals("2", String.valueOf(number));
}

Stringbuffer to int

@Test
public void stringbuffer_to_int() {

    StringBuffer buffer = new StringBuffer("2");

    assertEquals(2, Integer.parseInt(buffer.toString()));
}

StringBuilder to int

@Test
public void stringbuider_to_int() {

    StringBuilder builder = new StringBuilder("2");

    assertEquals(2, Integer.parseInt(builder.toString()));
}

String to Integer

@Test
public void string_to_integer() {

    Integer converted = Integer.valueOf("2");

    assertEquals(new Integer(2), converted);
}

Integer back to String

@Test
public void integer_to_string() {

    Integer integerToString = Integer.valueOf("2");

    assertEquals("2", integerToString.toString());
}