Java Integer.parseInt() Syntax
parseInt() is a static method of the Integer class. The second form takes a radix: the base of the number written in the string.
What is the difference between parseInt() and valueOf()?
Integer.parseInt() returns a primitive int. Integer.valueOf() returns an Integer object with the same value. Both methods accept the same strings and throw the same NumberFormatException.
Java String to Int Examples
The following are examples of converting a string to int in Java. Each example runs in the online Java code runner.
Convert a string to int with Integer.parseInt()
parseInt() reads the string as a signed decimal number. A leading minus or plus sign is allowed.
Convert a string to Integer with Integer.valueOf()
valueOf() returns an Integer object instead of a primitive int.
Handle a NumberFormatException
parseInt() throws a NumberFormatException if the string contains anything other than digits and one leading sign. Spaces, decimal points, an empty string and numbers outside the int range all fail. Wrap the call in a try-catch block when the string comes from user input or a file.
Convert a binary or hexadecimal string to int
Pass the radix as the second argument: 2 for binary, 8 for octal, 16 for hexadecimal.