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
.
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
.
Here we go
Do it manually:
Make sure there is no non-numeric data in the string.
Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.
For normal string you can use:
For String builder and String buffer you can use:
An alternate solution is to use Apache Commons' NumberUtils:
The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.
Apache NumberUtils API Version 3.4