How do I convert a String to an int in Java?
String myString = "1234";int foo = Integer.parseInt(myString);
If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException
, which of course you have to handle:
int foo;try { foo = Integer.parseInt(myString);}catch (NumberFormatException e){ foo = 0;}
(This treatment defaults a malformed number to 0
, but you can do something else if you like.)
Alternatively, you can use an Ints
method from the Guava library, which in combination with Java 8's Optional
, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;int foo = Optional.ofNullable(myString) .map(Ints::tryParse) .orElse(0)
For example, here are two ways:
Integer x = Integer.valueOf(str);// orint y = Integer.parseInt(str);
There is a slight difference between these methods:
valueOf
returns a new or cached instance ofjava.lang.Integer
parseInt
returns primitiveint
.
The same is for all cases: Short.valueOf
/parseShort
, Long.valueOf
/parseLong
, etc.
Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
int foo;String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exceptionString StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exceptiontry { foo = Integer.parseInt(StringThatCouldBeANumberOrNot);} catch (NumberFormatException e) { //Will Throw exception! //do something! anything to handle the exception.}try { foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);} catch (NumberFormatException e) { //No problem this time, but still it is good practice to care about exceptions. //Never trust user input :) //Do something! Anything to handle the exception.}
It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.