Java Program to Convert a String to Int

In this java program, we will learn about how to convert a string variable into integer(int) value. You can convert a String to Integer in Java in many ways such as by using Integer.parseInt(), Integer.valueOf() or new Integer().

Your application often reads data in the form of strings. You must convert it to an integer in order to extract a number from that string and use it for numerical operations. The method generally used to convert String to Integer in Java is parseInt() of String class.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert String to Int using parseInt() method

In this program, we will use the Integer.parseInt() method to convert the string variables into the int. parseInt() is a static method of Integer wrapper class in Java. The syntax of parseInt() method is as follows:

public static int parseInt(String s)
If you do not provide a valid string that is parsable int, Integer.parseInt() throws NumberFormatException.

public class StringToInt {
  public static void main(String[] args) {
    // Initializing string variables
    String str1 = "123";
    String str2 = "-456";

    int num1 = Integer.parseInt(str1);
    int num2 = Integer.parseInt(str2);

    System.out.println(num1);
    System.out.println(num2);
  }
}
Output
123
-456

Java Program to Convert String to Int using valueOf() method

You can also use Integer.valueOf() function to convert a string to int. The valueOf() method actually returns an object of the Integer class.

public class StringToInt2 {
  public static void main(String[] args) {
    // Initializing string variables
    String str1 = "123";
    String str2 = "-456";

    int num1 = Integer.valueOf(str1);
    int num2 = Integer.valueOf(str2);

    System.out.println(num1);
    System.out.println(num2);
  }
}
Output
123
-456