In Java, you can use Integer.parseInt(...)
or Integer.valueOf(...)
to convert a string to an integer, use Integer.parseUnsignedInt(...)
to convert a string to an unsigned integer. A NumberFormatException
will be thrown if the string does not contain a parsable integer
Integer.parseInt(...) and Integer.valueOf(...)
Integer.parseInt(String s)
parses the string arguments
as a signed decimal integer
String s = "10";
int n = Integer.parseInt(s);
System.out.println(n); // 10
Integer.parseInt(String s, int radix)
parses the string argument as a signed integer in the radix specified by the second argument
String s = "10";
int n = Integer.parseInt(s, 2);
System.out.println(n); // 2
Integer.parseInt(CharSequence s, int beginIndex, int endIndex, int radix)
parses theCharSequence
argument from the character atbeginIndex
toendIndex - 1
as a signed integer in the specifiedradix
String s = "a10b";
int n = Integer.parseInt(s, 1, 3, 2);
System.out.println(n); // 2
- The characters in the string must all be decimal digits, except the first character may be a minus (-) or plus (+) sign
String s = "-10";
int n = Integer.parseInt(s);
System.out.println(n); // -10
- A
NumberFormatException
will be thrown if the string does not contain a parsable integer
String s = "10a";
int n = Integer.parseInt(s); // throws NumberFormatException
Integer.parseInt(String s)
is backed byInteger.parseInt(String s, int radix)
with 10 as theradix
argumentInteger.valueOf(String s)
andInteger.valueOf(String s, int radix)
internally callInteger.parseInt(String s)
andInteger.parseInt(String s, int radix)
respectively
Integer.parseUnsignedInt(...) since Java 8+
Integer.parseUnsignedInt(String s)
parses the string arguments
as an unsigned decimal integer
String s = "10";
int n = Integer.parseUnsignedInt(s);
System.out.println(n); // 10
Integer.parseUnsignedInt(String s, int radix)
parses the string argument as an unsigned integer in the radix specified by the second argument
String s = "10";
int n = Integer.parseUnsignedInt(s, 2);
System.out.println(n); // 2
Integer.parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix)
parses theCharSequence
argument from the character atbeginIndex
toendIndex - 1
as an unsigned integer in the specifiedradix
String s = "a10b";
int n = Integer.parseInt(s, 1, 3, 2);
System.out.println(n); // 2
- The characters in the string must all be decimal digits, except the first character may be a plus (+) sign
String s = "+10";
int n = Integer.parseUnsignedInt(s);
System.out.println(n); // 10
- A
NumberFormatException
will be thrown if the string does not contain a parsable unsigned integer
String s = "-10";
int n = Integer.parseUnsignedInt(s); // throws NumberFormatException
Integer.parseUnsignedInt(String s)
is backed byInteger.parseUnsignedInt(String s, int radix)
with 10 as theradix
argument