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)
        numberList.forEach(number -> System.out.println(number));

the output :



We may get this error if the String is not an integer 

        try {
            integer = Integer.parseInt(notNumber);
        } catch (NumberFormatException nfe){

this code will throw a NumberFormatException :

java.lang.NumberFormatException: For input string: "123NA"
	at java.lang.NumberFormatException.forInputString(
	at java.lang.Integer.parseInt(
	at java.lang.Integer.parseInt(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at com.intellij.rt.execution.application.AppMain.main(

 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