Integer.parseInt()
or Integer.valueOf()
to convert a String to int or Integer.Lets convert String "123" to int using Integer.parseInt()
String stringNumber = "123";
int primitive = Integer.parseInt(stringNumber);
System.out.println("int = " + primitive);
The output will be :
primitive int = 123
Now we want to convert it to Integer Object with Integer.valueOf()
String stringNumber = "123";
Integer integer = Integer.valueOf(stringNumber);
System.out.println("Integer = " + integer);
Now the output is :
Object int = 123
You can use any of them because in java converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing.
primitive = integer;
integer = primitive;
Both are correct and will work.
public static void convertMultiNumbersStringToIntegerArray(){
String numbers = "1,2,3,4,5,6";
String separator = ",";
Pattern pattern = Pattern.compile(separator);
List<Integer> numberList = pattern.splitAsStream(numbers)
.map(Integer::valueOf)
.collect(Collectors.toList());
numberList.forEach(number -> System.out.println(number));
}
the output :
1
2
3
4
5
6
We may get this error if the String is not an integer
try {
integer = Integer.parseInt(notNumber);
} catch (NumberFormatException nfe){
nfe.printStackTrace();
}
this code will throw a NumberFormatException :
java.lang.NumberFormatException: For input string: "123NA"
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 org.newtutorials.java.convert.stringtoint.StringToInt.main(StringToInt.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
adding try / catch block we can handel it.
You can find and download the code on github :
Java String to int ot integer Example