Integer.parseInt() vs Integer.valueOf()

Naveen AnamaneniUpdated · 4 min read

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

Parse.java▶ Try it
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"));
    }
}
Output
43
Integer
-17
17
255
10
350.0
9000000000
false true

How it works

  1. parseInt returns an int, ready for arithmetic. valueOf returns an Integer object.
  2. A leading - or + is allowed.
  3. The second argument is the radix (base): "ff" in base 16 is 255, and "1010" in base 2 is 10.
  4. Every wrapper has its own parser: Double.parseDouble, Long.parseLong and so on.
  5. Boolean.parseBoolean returns true only for "true", ignoring case; anything else, even "YES", is false. It never throws.

When the Text Isn't a Number

BadInput.java▶ Try it
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()));
    }
}
Output
For input string: "12a"
For input string: " 42"
For input string: "3000000000"
For input string: ""
Cannot parse null string
42

How it works

  1. Letters, spaces, values too big for an int (3 billion) and empty strings all throw NumberFormatException.
  2. Even null throws NumberFormatException, not NullPointerException.
  3. 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

NeedUse
A number for arithmetic or an int fieldInteger.parseInt(s)
An object for a collection, or a nullable valueInteger.valueOf(s)
A number in another baseInteger.parseInt(s, radix)
An int that's already a primitive, boxedInteger.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

  1. Easy: Read three numbers from args, parse them with parseInt and print their sum. Run it with one bad argument and handle the exception.
  2. Harder: Write static int parseOrDefault(String s, int fallback) that strips the text, returns the number, or returns fallback for invalid or null input.

Quick check: parseInt vs valueOf

4 questions
1What does Integer.parseInt("42") return?
2What does Integer.parseInt(" 42") do?
3What is Integer.parseInt("ff", 16)?
4What does Boolean.parseBoolean("YES") return?

Key Takeaways

Was this tutorial helpful?

Lesson 162 of 482