How can I convert a String
to an int
in Java?
My String contains only numbers, and I want to return the number it represents.
For example, given the string "1234"
the result should be the number 1234
.
intjavastringtype-conversion
How can I convert a String
to an int
in Java?
My String contains only numbers, and I want to return the number it represents.
For example, given the string "1234"
the result should be the number 1234
.
Best Solution
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:(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'sOptional
, makes for a powerful and concise way to convert a string into an int: