![]() |
VOOZH | about |
Converting a String to an int in Java can be done using methods provided in the Integer class, such as Integer.parseInt() or Integer.valueOf() methods.
Example:
The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException if the string contains non-numeric characters.
12345
The Integer.valueOf() method converts a String to an Integer object instead of a primitive int. We can unbox it to an int.
Note: valueOf() method uses parseInt() internally to convert to integer.
217
If a string literal does not contain numeric values, calling the Integer.parseInt() or Integer.valueOf() methods will result in a NumberFormatException.
Example:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at StringToIntExample.main(StringToIntExample.java:10)