We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.
Scenario
It is generally used if we have to perform mathematical operations on the string which contains a number. Whenever we receive data from TextField or TextArea, entered data is received as a string. If entered data is in number format, we need to convert the string to an int. To do so, we use Integer.parseInt() method.
Signature
The parseInt() is the static method of Integer class. The signature of parseInt() method is given below:
public static int parseInt(String s)
Java String to int Example: Integer.parseInt()
Let's see the simple code to convert a string to an int in java.
int i=Integer.parseInt("200");
Let's see the simple example of converting String to int in Java.
Output:
Understanding String Concatenation Operator
Output:
Java String to Integer Example: Integer.valueOf()
The Integer.valueOf() method converts String into Integer object. Let's see the simple code to convert String to Integer in Java.
Output:
NumberFormatException Case
If you don't have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.
Output: