How to convert a String into an int in Java
With Java 11, there are several ways to convert an int to a String type. Use the parseInt method of the Java Integer class to translate a string to an integer. If the string cannot be converted into an int, the function attempts to convert it to an int and raises a NumberformatException. In this blog, we are going to learn about converting the String into an int in Java.
For converting a String value to an integer value, we can utilize the parseInt(String str) method of the Integer wrapper class. With Java 11, there are several ways to convert an int to a String type:
-
Integer.parseInt()
String str = "1234"; int result = Integer.parseInt(str);
-
Integer.valueOf()
String str = "1234"; int result = Integer.valueOf(str).intValue();
-
Integer constructor
String str = "1234"; Integer result = new Integer(str);
-
Integer.decode
String str = "1234"; int result = Integer.decode(str);
Use the parseInt method of the Java Integer class to translate a string to an integer. If the string cannot be transformed into an int type, the parseInt function attempts to convert the string to an int and raises a NumberFormatException.
Despite whatever exceptions it might throw, use this:
int i = Integer.parseInt(myString);
If the String represented by the variable myString is an acceptable integer, such as “1234”, “200,” or “1,” it will be transformed to a Java int. The code should be a little bit longer to account for this as if it fails for any reason, the update may throw a NumberFormatException.
To avoid a NumberFormatException, check the Java String to Int conversion function, for instance.
public class BehindJava {
public static void main(String[] args) {
// String s = "test"; // Use this if you want to test the exception below
String s = "1234";
try {
// The String to int conversion happens here
int i = Integer.parseInt(s.trim());
// Print out the value after the conversion
System.out.println("int i = " + i);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
Output:
int i = 1234
The Integer parseInt process will throw a NumberFormatException if the change attempt fails, in this case if you try to convert the Java String test to an int. You must handle this exception in a try/catch block.