Integer.parseInt() vs Integer.valueOf()
Numbers often arrive as text: from a form field, a file, args on the command line, or a web request. Integer offers two ways to convert "42" into a number: Integer.parseInt("42"), which returns a primitive int, and Integer.valueOf("42"), which returns an Integer object. They parse in exactly the same way; the difference is only in what comes back.
Both Side by Side
public class Parse {
public static void main(String[] args) {
int a = Integer.parseInt("42");
Integer b = Integer.valueOf("42");
System.out.println(a + 1);
System.out.println(b.getClass().getSimpleName());
System.out.println(Integer.parseInt("-17"));
System.out.println(Integer.parseInt("+17"));
System.out.println(Integer.parseInt("ff", 16));
System.out.println(Integer.parseInt("1010", 2));
System.out.println(Double.parseDouble("3.5e2"));
System.out.println(Long.parseLong("9000000000"));
System.out.println(Boolean.parseBoolean("YES")
+ " " + Boolean.parseBoolean("True"));
}
}43
Integer
-17
17
255
10
350.0
9000000000
false trueHow it works
parseIntreturns anint, ready for arithmetic.valueOfreturns anIntegerobject.- A leading
-or+is allowed. - The second argument is the radix (base):
"ff"in base 16 is 255, and"1010"in base 2 is 10. - Every wrapper has its own parser:
Double.parseDouble,Long.parseLongand so on. Boolean.parseBooleanreturnstrueonly for"true", ignoring case; anything else, even"YES", isfalse. It never throws.
When the Text Isn't a Number
public class BadInput {
public static void main(String[] args) {
String[] inputs = {"12a", " 42", "3000000000", ""};
for (String s : inputs) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
try {
Integer.parseInt(null);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
System.out.println(Integer.parseInt(" 42 ".strip()));
}
}For input string: "12a"
For input string: " 42"
For input string: "3000000000"
For input string: ""
Cannot parse null string
42How it works
- Letters, spaces, values too big for an
int(3 billion) and empty strings all throwNumberFormatException. - Even
nullthrowsNumberFormatException, notNullPointerException. strip()removes surrounding spaces, the most common fix for user input.
NumberFormatException is unchecked, so the compiler won't remind you; wrap user input in try-catch.
Which One to Use
| Need | Use |
|---|---|
A number for arithmetic or an int field | Integer.parseInt(s) |
| An object for a collection, or a nullable value | Integer.valueOf(s) |
| A number in another base | Integer.parseInt(s, radix) |
An int that's already a primitive, boxed | Integer.valueOf(int) (cached), never new Integer(...) |
Common Mistakes
Forgetting to strip spaces. " 42" fails; call strip() first.
Parsing numbers larger than int. Use Long.parseLong or new BigInteger(s).
Expecting parseBoolean("yes") to be true. Only "true" (any case) is true.
Interview Corner
What is the difference between Integer.parseInt() and Integer.valueOf()?
Both convert a string to a number with the same rules. parseInt returns a primitive int; valueOf returns an Integer object, reusing cached objects for -128 to 127. Use parseInt when you need an int value and valueOf when you need an object, such as for a collection. Both throw NumberFormatException for invalid input.
Practice
- Easy: Read three numbers from
args, parse them withparseIntand print their sum. Run it with one bad argument and handle the exception. - Harder: Write
static int parseOrDefault(String s, int fallback)that strips the text, returns the number, or returnsfallbackfor invalid or null input.
Key Takeaways
Was this tutorial helpful?