HelloKoding

Practical coding guides

String Conversion in Java

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

Use Integer.parseInt and Integer.valueOf

  • Integer.parseInt(String s) parses the string argument s 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 the CharSequence argument from the character at beginIndex to endIndex - 1 as a signed integer in the specified radix
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 by Integer.parseInt(String s, int radix) with 10 as the radix argument
  • Integer.valueOf(String s) and Integer.valueOf(String s, int radix) internally call Integer.parseInt(String s) and Integer.parseInt(String s, int radix) respectively

Use Integer.parseUnsignedInt since Java 8+

  • Integer.parseUnsignedInt(String s) parses the string argument s 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 the CharSequence argument from the character at beginIndex to endIndex - 1 as an unsigned integer in the specified radix
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 by Integer.parseUnsignedInt(String s, int radix) with 10 as the radix argument
Follow HelloKoding