skip to content

What is the difference between Integer.parseInt and Integer.valueOf, and how do radix overloads and parsing errors work?

level: middleimportance: should knowfreq 60%

answer

  1. parseInt -> int, valueOf -> Integer
  2. valueOf may return cached object
  3. radix overload 2..36
  4. bad/overflow input -> NumberFormatException (unchecked)
  5. parseUnsignedInt + toHexString/toBinaryString

basics

~20 s

parseInt returns a primitive int; valueOf returns an Integer object (possibly from the cache). Both can take a radix (e.g. base 16) and both throw NumberFormatException on bad input. Use parseInt when you want an int, valueOf when you need the wrapper.

solid answer

~40 s

Integer.parseInt(String) returns a primitive int. Integer.valueOf(String) parses the same way but returns an Integer object, and because it ultimately calls valueOf(int) it may hand back a cached object for small values. Both have a radix overload: parseInt("ff", 16) and valueOf("1010", 2) parse in the given base (2..36). Both throw NumberFormatException (a RuntimeException) for null, empty, malformed, or out-of-range strings. There are siblings: parseUnsignedInt handles values that exceed Integer.MAX_VALUE by interpreting the bits as unsigned, and the toString-side has toBinaryString, toHexString, and toOctalString for the reverse direction. Rule of thumb: use parseInt when you just need an int (no allocation); use valueOf when you need an Integer for a collection or nullable field. Catch or validate against NumberFormatException for any external input.

code

java · 12 lines
java
int dec = Integer.parseInt("42");        // 42
int hex = Integer.parseInt("ff", 16);    // 255
Integer boxed = Integer.valueOf("42");   // Integer (cached)

try {
    Integer.parseInt("12a");             // throws
} catch (NumberFormatException e) {
    // handle bad input
}

String h = Integer.toHexString(255);     // "ff"
int big = Integer.parseUnsignedInt("4000000000"); // > MAX_VALUE

go deeper

for a junior

Knows parseInt converts a String to an int and that bad input throws an exception.

for a middle

Distinguishes parseInt (int) from valueOf (Integer, maybe cached), uses the radix overload, and handles NumberFormatException.

for a senior

Explains unchecked-exception implications, parseUnsignedInt, and the toBinaryString/toHexString reverse direction including two's-complement output.

for a principal

Sets parsing/validation conventions for untrusted input (fail-fast, defensive parsing), and weighs allocation cost of valueOf in hot paths.

## The two methods Both convert text into a number, but their **return types differ**: - `Integer.parseInt(String s)` returns a **primitive `int`**. No object is created. - `Integer.valueOf(String s)` returns an **`Integer` wrapper**. Internally it parses to an int and then calls `Integer.valueOf(int)`, so for values in -128..127 it may return a **cached** object rather than a new one. ```java int i = Integer.parseInt("42"); // primitive Integer w = Integer.valueOf("42"); // wrapper (cached here) ``` Choose `parseInt` when you want a primitive (arithmetic, no allocation); choose `valueOf` when you need an `Integer` (to put in a `List<Integer>`, or where `null` is meaningful). ## Radix (base) overloads A **radix** is the number base. Both methods have an overload taking a radix from 2 to 36 (digits 0-9 then a-z): ```java Integer.parseInt("ff", 16); // 255 (hexadecimal) Integer.parseInt("1010", 2); // 10 (binary) Integer.parseInt("777", 8); // 511 (octal) Integer.valueOf("z", 36); // 35 ``` The single-argument form is just radix 10. A radix outside 2..36, or a digit not valid for the base, throws. ## NumberFormatException When the string is `null`, empty, contains non-digit characters (other than a leading sign), or represents a value that **overflows** the type's range, the method throws **`NumberFormatException`**. This is an *unchecked* (Runtime) exception — the compiler does not force you to catch it, so you must remember to validate or wrap external input. ```java Integer.parseInt("12a"); // NumberFormatException: not all digits Integer.parseInt("9999999999"); // NumberFormatException: overflows int Integer.parseInt(""); // NumberFormatException: empty ``` A leading `+` or `-` is allowed (`parseInt("-7")` is fine); a leading/trailing space is **not**. ## Unsigned parsing An `int` is signed and tops out at `Integer.MAX_VALUE` (2147483647). `Integer.parseUnsignedInt("4000000000")` accepts values up to 4294967295 by storing them in the same 32 bits but **interpreting** them as unsigned; the stored int may *look* negative if you print it normally, so pair it with `Integer.toUnsignedString` / `Integer.toUnsignedLong` to read it back. ## The reverse direction: toXxxString For formatting an int back into a based string there are `Integer.toBinaryString(n)`, `Integer.toOctalString(n)`, `Integer.toHexString(n)`, and the general `Integer.toString(n, radix)`. These produce **unsigned** two's-complement representations for the binary/octal/hex variants (so `toHexString(-1)` is `"ffffffff"`). ## Summary table | Need | Use | |---|---| | primitive int from text | `parseInt` | | Integer object from text | `valueOf` | | non-decimal base | the radix overload | | values above MAX_VALUE | `parseUnsignedInt` | | int -> hex/bin/oct text | `toHexString` / `toBinaryString` / `toOctalString` | Always guard parsing of untrusted input against `NumberFormatException`.

  • Is NumberFormatException checked or unchecked, and why does that matter?
    It is unchecked (extends RuntimeException, via IllegalArgumentException). The compiler does not force handling it, so you must remember to validate or catch it when parsing untrusted input.
  • When would you prefer parseInt over valueOf?
    When you only need a primitive int for arithmetic or comparison; parseInt avoids creating a wrapper object (no allocation, no boxing).

saying these in an interview costs you the question

  • Saying parseInt returns an Integer
  • Thinking NumberFormatException is checked and must be declared
  • Assuming valueOf(String) always allocates a new object
  • Believing parseInt accepts surrounding whitespace
  • Confusing radix (input base) with the toXxxString output methods

context