String to int in Java
Last Updated :
22 Nov, 2024
Improve
Converting a String to an int in Java can be done using methods provided in the Integer
class, such as Integer.parseInt()
or Integer.valueOf()
methods.
Example:
The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException
if the string contains non-numeric characters.
// Java Program to demonstrate
// String to int conversion using parseInt()
public class StringToInt {
public static void main(String[] args) {
String s = "12345";
// Convert the string to an integer
// using Integer.parseInt()
int n = Integer.parseInt(s);
System.out.println("" + n);
}
}
Output
12345
Other Ways to Convert String to int
Using Integer.valueOf() Method
The Integer.valueOf() method converts a String to an Integer object instead of a primitive int. We can
unbox it to an int.
Note: valueOf() method uses parseInt() internally to convert to integer.
Example:
// Java ProgramConvert String to int
// using Integer.valueOf() Method
public class StringToInt {
public static void main(String[] args) {
// Convert String to Integer using valueOf()
String s = "217";
// Convert the string to an Integer object
// using Integer.valueOf()
int n = Integer.valueOf(s);
System.out.println("" + n);
}
}
Output
217
Handling Errors for Non-Numeric Strings
If a string literal does not contain numeric values, calling the Integer.parseInt() or Integer.valueOf() methods will result in a NumberFormatException.
Example:
// Java Program to Demonstrate Working of parseInt() Method
// where NumberFormatException is Thrown
public class StringToIntExample {
public static void main(String[] args) {
// NumberFormatException due to empty string
String s1 = "";
int n1 = Integer.parseInt(s1);
// NumberFormatException due to non-numeric string
String s2 = "geeksforgeeks";
int n2 = Integer.parseInt(s2);
System.out.println(n1);
System.out.println(n2);
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at StringToIntExample.main(StringToIntExample.java:10)