How to convert String to Integer in Java
There are a couple of methods which are being followed in order to convert a number represented as a String into an integer data type. The method which is widely used to convert String to int is known as parseInt().
Integer.parseInt()
parseInt() is the static method of Integer class. Let us look at an example and understand how parseInt() works.
Output
Let us look at the output of the above example code.
Here we can clearly differentiate between String data type and int data
type. The second
output statement, “555100” is a String which concatenates the
String “555” with “100”
whereas the next output statement, 655 is of the type int which adds
555 with 100.
There is another method which is used to convert String to int in
Java.
Integer.valueOf()
The method parseInt() converts String to a primitive int, whereas the method valueOf() converts String to an Integer object. Let us look at an example depicting valueof() method.
Output
Let us look at the output of the above example code.
It should be noted that valueOf() internally uses parseInt() to convert String to int.
NumberFormatException
In certain scenarios, when the String which is being converted to int does
not contain a
parsable integer, then the NumberFormatException is thrown.
Let us look at an example for
those scenarios.
Output
Let us look at the output of the above example code.
Here the String which is being parsed is “200AB”. It contains the
characters “AB” concatenated with "200", which
cannot be parsed to int. Therefore, the program throws an exception.
Now, let us look at the code which will handle this exception.
Output
Let us look at the output of the above example code.
The program is self explanatory how the exception case is handled using the catch clause, which is executed when the program runs into some kind of run time error.
Summary
To convert String data type to Integer data type in Java, we have a couple of methods which are being followed widely, namely, parseInt() and valueOf(). Both these methods are static method of Integer class. The method valueOf() uses the method parseInt() internally in order to convert a String to an integer data type. However, there are at times when the program throws a NumberFormatException when the String entered is not parsable in number format.