How To Convert String To Int In Java?

Java programming language provides the String type in order to store single or multiple characters. The int or integer type is used for numbers in a mathematical way which can be used in mathematical calculations. One of the most popular Java operations is converting string to int.

Convert String To Int with parseInt()

The parseInt() method is used to convert provided string into the integer. The parseInt() method is a static method provided via the Integer object. There is no need to create an instance for parseInt() method. The syntax of the parseInt() method is like below.

Integer.parseInt(S);
  • S is a string value or object or variable.

In the following example, we convert different strings into the integer using the parseInt().

//Integer.parseInt() method  
public class ExampleApp{
    public static void main(String args[]) {
        //Create String  
        String s = "123";
        //Converting String into int using Integer.parseInt()  
        int i = Integer.parseInt(s);
        //Printing converted integer
        System.out.println(i);
    }
}
123

Convert String To Int with valueOf()

Another method to convert string o integer is the Integer.valueOf() method. The valueOf() is a static method provided via the Integer object. The syntax of the valueOf() method is like below.

Integer.valueOf(S);
  • S is a string value or object or variable.

In the following example, we convert the string into an integer using the valueOf() method.

//Integer.parseInt() method  
public class ExampleApp{
    public static void main(String args[]) {
        //Create String  
        String s = "123";
        //Converting String into int using Integer.parseInt()  
        int i = Integer.valueOf(s);
        //Printing converted integer
        System.out.println(i);
    }
}

Conversion Exception (NumberFormatException)

During the string to integer conversion, some errors or exceptions may occur. Generally the NumberFormatException occurs if we try to convert a non-numeric string into an integer.

//Integer.parseInt() method  
public class ExampleApp{
    public static void main(String args[]) {
        //Create String  
        String s = "abc";
        //Converting String into int using Integer.parseInt()  but we will get an Exception
        int i = Integer.valueOf(s);
        //Printing converted integer
        System.out.println(i);
    }
}
Compile by: javac StringToIntegerExample3.java

Run by: java StringToIntegerExample3

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"
 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 StringToIntegerExample3.main(StringToIntegerExample3.java:4)

Leave a Comment