How to Convert String to int in Java

This tutorial will teach you how to convert a String value to an int value in Java.

Convert String to int

To convert String value to an int value, you can use Integer.parseInt() function. The parseInt() method accepts a String value as a parameter and returns an int value as a result.

Successful conversion

public class JavaStringToInt {
    public static void main(String[] args) {
        String numberTen = "10";
        int numberTenInt  = Integer.parseInt(numberTen);

        // This will print 10
        System.out.println(numberTenInt);
    }
}

In the above code example, parseInt() method accepted valid input parameters. Do you think the following values can also be converted to a primitive int as well?

"-10", " 10", "10 ", "0"

Yes! All above-listed values can be converted to int just fine. But what do you think will happen if we provide a value that cannot be converted? Let’s have a loot at in next.

Invalid input parameter

If a String value cannot be converted to a primitive int data type, then a NumberFormatException will be thrown.  Notice in the code snippet below that the parseInt() method accepts “1a” as an input parameter. Because “1a” cannot be converted to a primitive int data type, the result will be a NumberFormatException.

public class JavaStringToInt {
    public static void main(String[] args) {
        String numberToConvert = "1a";
        int numberTenInt  = Integer.parseInt(numberToConvert);

        System.out.println(numberTenInt);
    }
}

How about the following values? Do you think they will convert to int just fine or result in a NumberFormatException?

"1.5", "zero", "999999999999999999", "", "null","10+10"

The correct answer is NumberFormatException. All above-listed values cannot be converted to int data type, resulting in a NumberFormatException.

Convert String to an Integer

If you need to convert String to an Integer data type instead, then you can use Integer.valueOf() method. This method accepts the String value as an input parameter and returns an Integer object as a result.

public class JavaStringToInt {
    public static void main(String[] args) {
        String numberTen = "10";
        Integer numberTenObj = Integer.valueOf(numberTen);

        // Prints out 10
        System.out.println(numberTenInt);
    }
}

I hope this short blog post was of some value to you. But before you go, please check other Java tutorials or Spring Boot tutorials that I have.

Happy learning!