Here’s an example of converting a String to an int primitive using Integer.parseInt()
String number = "100";
int integer = Integer.parseInt(number);
Here’s a unit test for converting a String to an int in java
@Test
public void convertStringToInt() {
String number = "100";
int integer = Integer.parseInt(number);
System.out.println(integer);
assertTrue("Confirm number is the string converted to int", Integer.parseInt(number) == 100);
}
Output
100
Heres an example of converting a String to an Integer object using Integer.valueOf()
String number = "10";
Integer result = Integer.valueOf(number);
Here’s a unit test for converting a String to an Integer object in java
@Test
public void convertStringToInteger() {
String number = "100";
Integer integer = Integer.valueOf(number);
System.out.println(integer);
assertTrue("Confirm number is the string coverted to Integer", Integer.valueOf(number) == 100);
assertThat("Confirm number is the string coverted to Integer", Integer.valueOf(number),
is(instanceOf(Integer.class)));
}
Output
100
Exceptions
NumberFormatException
Both Integer.parseInt() and Integer.valueOf(number) will throw a NumberFormatException if the String isnt in the correct format for conversion to a number
Here’s a junit test as an example
@Test
public void convertInvalidStringToInt() {
String number = "100A";
int integer = Integer.parseInt(number);
System.out.println(integer);
assertTrue("Confirm number is the string coverted to int", Integer.parseInt(number) == 100);
}
And heres the stacktrace with the NumberFormatException
java.lang.NumberFormatException: For input string: "100A"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
References
The Integer class provides methods for converting an int
to a String
and a String
to an int
, and other methods for dealing with int