How to Convert String to Integer in Java

How to convert String to int in Java

You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so, you need to perform the conversion from String to int.

You can convert String to int in two ways:

  • Using Integer.parseInt() method
  • Using Integer.valueOf() method

Using Integer.parseInt() method

The paresInt() is the static method of Integer wrapper class under java.lang package.

Example-

In the following example, number is a variable of type String that contains digits “10” as string. num1 is a variable of type integer that contains value 20. num2 is the variable of type integer which stores the converted value of str. Integer is a class. paresInt() is the static method that takes str as an argument and returns a primitive int value. sum is a variable of type integer which stores the value after addition. The println statement prints the value of sum.

Output-

Remember: All characters must be in digits; the number can have a minus sign.

Valid Conversion

  • String number=”-369”;

Invalid Conversion

  • String number=”369a”;
  • String number=”abcd”;

If you define a String as above, Integer.parseInt() throws “NumberFormatException”, because it is not a valid conversion. 

Exception

Using Integer.valueOf() method

Integer.valueOf() works same as Integer.parseInt(String). It also converts a String to int value. It also throws NumberFormatException.

Example-

In the following example, str is a variable of type String that contains digits “-10” as string. num1 is a variable of type integer that contains value 110. num2 is a variable of type integer that stores the converted value of str. Integer is a wrapper class. valueOf() is the method that returns an integer instance representing the specified int value.  val is a variable that stores the sum of num1 and num2. First println statement prints the String str and second println prints the value of val after performing addition.

Output-

Difference Between Integer.valueOf() and Integer.parseInt()

There is a difference between Integer.valueOf() and Integer.parseInt(). The Integer.valueOf() method returns an object of Integer class whereas the Integer.parseInt() method returns a primitive int value.

If you need the primitive int datatype, then use parseInt() method. If you want wrapper Integer object, then use the valueOf() method.