Java String FAQ: How do I convert a String to an int with Java?
Answer: You can convert a Java String to an int using the parseInt() method of the Java Integer class. This method serves the purpose of converting a Java String to int data type. Let's take a look at an 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 Java String to int class, 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 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 trim() method of the Java String class, but in a real-world program you should use it, so that's why I show it here.
While I'm in the Java String to int neighborhood, here are a few related notes about Java and the String and Integer classes:
Integer.toString(int i) is used to convert in the other direction, from a Java into to a Java String.valueOf() method of the Integer class instead of the parseInt() method.I hope this "Java String to int" example is 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!
Post new comment