Java parse String into int

Java string to int

String which are numbers can be parsed to integer in Java by using method parseInt():

String num = "42";
int res = Integer.parseInt(num);
System.out.println(res);

result:

42

Alternatively you can use valueOf:

String num = "42";
Integer res = Integer.valueOf(num);		
System.out.println(res);

result:

42

The difference between parseInt and valueOf is the return type. The first one returns the primitive type int while the second one return the wrapper class Integer.

Java int to string

If you want to do the reverse operation to convert integer value into string then you can use method toString() for Integer and conversion for int:

Integer num3 = 42;
System.out.println(res1);
int num4 = 42;
String num5 = new Integer(res).toString();
System.out.println(num3);

result:

42
42

Error NumberFormatException

If you are trying to convert string which contains invalid number then you will get error:

String num = "42a";
int res = Integer.parseInt(num);

result:

Exception in thread "main" java.lang.NumberFormatException: For input string: "42a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at String.StringToInt.main(StringToInt.java:7)

Reference

Related Article