Java String to int FAQ: How do I convert a String to an int data type in Java?
Answer: You convert a String to an int using the parseInt method of the Java Integer class. The parseInt method converts the String to an int, and throws a NumberFormatException when the String can't be converted to an int type.
Let's take a look at two short examples.
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 can throw a NumberFormatException, so your code should be a little bit longer to account for this, as shown in the next example.
Here's the source code for a complete example program that demonstrates this Java String to int conversion process:
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());
}
}
}
As you can see from this example, the Integer.parseInt(s.trim()) method is used to convert from the String s to the int 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.
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.valueOf() method of the Integer class instead of the parseInt() method.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.
Thanks, this String to int
Thanks, this String to int conversion worked great for me.
Thanks man
Thanks man
Simple and easy
I was hoping there was a pre-built method for this. Thanks!
works great.. good found..
works great.. good found..
Post new comment