Convert String to int or Integer Java 8

In Java you can use 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.

Now we will transform a string that contains multiple numbers("1,2,3,4,5,6") to a List of Integers with Java 8 sintax

    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

NumberFormatException

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

Category: Java Tutorials