Java String/int FAQ: How do I convert a Java String to an int?
Solution
The most direct solution to convert a Java string to an integer is to use the parseInt method of the Integer class:
int i = Integer.parseInt(myString);
parseInt converts the String to an int, and throws a NumberFormatException if the string can’t be converted to an int type. For more information, see the following two examples. Therefore, a well-written function needs to account for this possible exception.
Example 1: A basic Java “String to int” conversion example
Ignoring the exception it can throw, all you need to convert a String to int is this one line of code:
int i = Integer.parseInt(myString);
If the String represented by the variable myString is a valid integer like “1”, “200”, and so on, it will be converted to a Java int. If it fails for any reason, the conversion will throw a NumberFormatException, so your code should be a little bit longer to account for this, as shown in the next example.
Example 2: A complete “String to int” example
Here’s the source code for a complete example program that demonstrates the Java String to int conversion process, handling for a possible NumberFormatException:
public class JavaStringToIntExample
{
public static void main (String[] args)
{
// String s = "fred"; // use this if you want to test the exception below
String s = "100";
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());
}
}
}
Discussion
As you can see from this example, the Integer.parseInt(s.trim()) method is used to convert from the string s to the integer i in this line of code:
int i = Integer.parseInt(s.trim());
If the conversion attempt fails -- for instance, if you try to convert the Java String fred to an int -- the Integer parseInt method will throw a NumberFormatException, which you should handle in a try/catch block.
In this example, I don’t really need to use the String class trim() method, but in a real-world program you should use it, so that's why I’ve shown it here.
Related notes
While I’m in this neighborhood, here are a few related notes about the String and Integer classes:
Integer.toString(int i)is used to convert in the other direction, from an int to a Java String.- If you're interested in converting a
Stringto anIntegerobject, use thevalueOf()method of the Integer class instead of theparseInt()method. - If you want to convert strings to other Java primitive fields, for example, a long, use methods like
Long.parseLong(), and so on.
Summary
I hope this Java String to int example has been helpful. If you have any questions or comments, just leave a note in the Comments section below.

