skip to content

Wrapper Classes & Number Caching

Wrapper mechanics and the valueOf caches — small Integers, Shorts, Bytes, Longs and Characters are shared, so == is true for 127 and false for 128. Interviewers use that puzzle constantly, and follow up with parsing, radix conversion and the bit-manipulation utilities.

part ofJavaread it →
on this pageshow

questions

6

What is the difference between int and Integer in Java, and when should a field, parameter or return type use each?

level: juniorimportance: must knowfreq 85%

answer

  1. value versus object
  2. which one can be null
  3. what == compares for each
  4. what a type argument must be
  5. does absence mean something here?

basics

~20 s

An int holds a 32-bit value and cannot be null; an Integer variable refers to an immutable object or null, and Integer works as a type argument. Use int by default, and Integer where absence matters or generics require it.

solid answer

~50 s

`int` is a primitive: a variable holds the 32-bit value itself, never `null`. `Integer` is a final class wrapping one `int`: a variable holds a reference to an object, or `null`, so `==` on two `Integer`s compares references and you compare values with `equals`. Only `Integer` can be a type argument, as in `List<Integer>`; `List<int>` does not compile. An `Integer` can also cost an extra object, about 16 bytes on a 64-bit HotSpot at default flags, plus the reference. So default to `int` for fields, parameters and return types whenever a value always exists. Use `Integer` where "no value" is a real state, such as a nullable database column, and in generic code. For a result that may be absent, return `OptionalInt`, because a null `Integer` throws `NullPointerException` as soon as a caller unboxes it.

code

java · 24 lines
java
import java.util.Map;
import java.util.OptionalInt;

public class RetryPolicy {
    private int attempts;        // 0 until assigned; a count always exists
    private Integer maxAttempts; // null until assigned: no limit configured

    void configureLimit(int max) {
        maxAttempts = max;       // boxed on assignment
    }

    OptionalInt limit() {
        return maxAttempts == null ? OptionalInt.empty() : OptionalInt.of(maxAttempts);
    }

    void recordAttempt() {
        attempts++;              // maxAttempts++ here would throw while it is null
    }

    static int retriesFor(Map<String, Integer> byService, String service) {
        Integer configured = byService.get(service); // null when there is no mapping
        return configured == null ? 0 : configured;  // decide before unboxing
    }
}

go deeper

for a junior

Recall the core contrast: int holds a value and cannot be null, while Integer is an object reference that can be. Say that List<int> does not compile and that equals, not ==, compares two Integer values.

for a middle

Explain the mechanics: boxing and unboxing conversions, the intValue call that throws on null, the final value field that makes Integer immutable, and why changing a field's type moves its default from 0 to null.

for a senior

Show judgment about nullable numbers in production: an Integer field or map lookup is a hidden null path, so keep null at the boundary, decide before unboxing, and return OptionalInt for absent results. Keep hot paths on primitives.

for a principal

The tradeoff is modelling against cost: Integer expresses absence and fits generic APIs, but adds indirection and null paths. Set primitives as the team default, review the exceptions, and enforce the rule with static analysis instead of style comments.

## Two types for one kind of number `int` is a **primitive type**: a variable of type `int` holds a 32-bit signed two's-complement value directly. `Integer` is a **wrapper class**, declared `public final class Integer extends Number`, and each instance contains a single field, `private final int value`. Because that field is final, an `Integer` object never changes after it is created. The compiler converts between the two. **Boxing** turns an `int` into a reference to an `Integer`, and **unboxing** turns an `Integer` into an `int`, as if by calling `intValue()`. Those automatic conversions first shipped in Java 5 (1.5), and they are covered in depth with autoboxing. ## The differences side by side | Aspect | `int` | `Integer` | |---|---|---| | A variable holds | The 32-bit value | A reference to an object, or `null` | | `null` | `int x = null;` does not compile | Legal; unboxing it throws `NullPointerException` | | Default as a field | `0` | `null` | | `==` with the same type | Compares the numbers | Compares the references | | Storage | 32 bits in the field or array element | A reference, plus an object unless one is shared | | Type argument | `List<int>` does not compile | `List<Integer>` is the normal form | | Members | None | Instance methods and static helpers | ## Null and identity - **Absence.** An `int` always has a value. An `Integer` can be null, so on a `Map<String, Integer>`, `int n = map.get(key);` compiles and then throws when the map has no mapping for that key, because `Map.get` returns `null` in that case. - **Defaults.** An unassigned `int` field holds `0` and an unassigned `Integer` field holds `null`. The `Integer` can tell "never set" apart from zero, but `count++` on it throws until it has a value. - **Identity.** `==` on two `Integer` operands compares references. Whether equal values share one object depends on the `Integer.valueOf` cache, the subject of the 127-versus-128 puzzle, so compare values with `equals`. With one `int` and one `Integer`, `==` unboxes the wrapper and compares numbers. - **Value-based.** JEP 390 in Java 16 designated the wrappers as value-based. Programs should not tell equal instances apart by identity and should not synchronize on them, and `javac` warns about `synchronized` on an `Integer` by default. - **Constructors.** `new Integer(5)` has been deprecated since Java 9, though at JDK 25 and 27 it is not marked for removal. Use `Integer.valueOf` or plain boxing. ## Memory An `int` needs 32 bits and no separate object. An `Integer` needs a reference and, unless it shares a cached instance, its own object. `Instrumentation.getObjectSize`, which returns an implementation-specific approximation, reports 16 bytes for an `Integer` on a 64-bit HotSpot at default flags. That figure is the same on JDK 27, where compact object headers are on by default (JEP 534), and on JDK 25, where they are off by default. The same tool reports 4016 bytes for an `int[1000]`, and also for an `Integer[1000]` with compressed references, but the second figure counts only the references and none of the `Integer` objects. How large that gap gets for a whole list is a separate question about arrays and boxed lists. ## Generics A type argument must be a reference type or a wildcard, so `List<int>` fails with `unexpected type`. Collections therefore take and return `Integer`, and every `int` passing through them is boxed or unboxed. Arrays have no such limit, so `int[]` is legal. The reason for that asymmetry belongs to the generics restrictions. ## Which to use where - **Field:** use `int` when a value always exists and zero is a sensible start. Use `Integer` when "not set" differs from `0`, such as a nullable database column or an optional property, and accept that every read needs a null decision. - **Parameter:** use `int` so that callers cannot pass null and the method needs no check. Use `Integer` only when null has a defined meaning, and consider an overload without the parameter instead. - **Return type:** use `int` when a result always exists. When it may not, prefer `OptionalInt`, whose Javadoc calls it primarily intended as a return type where there is a clear need to represent "no result". A nullable `Integer` return hides that case, because `int n = find(key);` compiles. - **Generic code:** use `Integer` where a type argument is required, such as `Map<String, Integer>`, and unbox to `int` at the boundary, after deciding what a missing value means. - **Numeric hot paths:** prefer `int` and `int[]`, because each boxed value can mean another object. Those costs are covered with autoboxing.

  • Why does list.remove(1) on a Java List<Integer> remove by index and not the value 1?
    Overload resolution first looks for applicable methods without boxing. `remove(int index)` applies in that phase, so it wins over `remove(Object)`. To remove by value, pass a reference: `list.remove(Integer.valueOf(1))`. Whether the argument's type is `int` or `Integer` therefore decides what the call means.
  • Why does count++ on an Integer not affect other variables holding the same object?
    `Integer` is immutable, because its `value` field is `private final`. `count++` unboxes `count`, adds one, boxes the result and stores that reference back in `count`. Other variables keep the old reference and the old value. If `count` is null, the unboxing step throws `NullPointerException`.
  • Should Java code create wrapper objects with new Integer(5)?
    No. The `Integer` constructors have been deprecated since Java 9, and `Integer.valueOf` or plain boxing is the usual choice, because it may reuse cached instances. `Integer` is also a value-based class, so code should not depend on a fresh identity from a constructor. At JDK 25 and 27 the constructors are deprecated but not marked for removal.

  • int and Integer are the same type, and the compiler treats them identically.
  • An Integer field defaults to 0, just as an int field does.
  • Comparing two Integer variables with == compares their numeric values.
  • List<int> compiles, because autoboxing converts the type argument.
  • Autoboxing makes the two interchangeable, so Integer everywhere costs nothing.
  • An Integer is mutable, so count++ changes the object other variables share.

Integer wrapper class
Java 1.0
Autoboxing and unboxing
Java 1.5
Generics
Java 1.5
Wrapper classes designated value-based
Java 16
OptionalInt
Java 1.8

Assumes JDK 27; the 16-byte Integer is the size at default flags on both 27 and 25, whose compact object header defaults differ.

context

open as a page

What are wrapper classes in Java, and why do they exist?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Wrapper classes like Integer, Long, Double, Boolean, and Character are object versions of the eight primitive types. They exist because generics and collections only hold objects, not primitives, and they add helper methods and constants.

open as a page

Why does comparing two Integer values with == give true for 127 but false for 128?

level: middleimportance: must knowfreq 85%

basics

~20 s

Integer.valueOf caches the small values -128..127, so autoboxing 127 twice returns the same object and == is true. 128 is outside the cache, so two new objects are created and == compares references, giving false. Always use .equals for wrappers.

open as a page

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

level: middleimportance: should knowfreq 60%

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.

open as a page

Why is Integer.compare(a, b) safer than writing a - b, and what is the Math.abs(Integer.MIN_VALUE) quirk?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Integer.compare(a, b) never overflows, but the old trick a - b can overflow when the difference exceeds int range and then return the wrong sign. Similarly Math.abs(Integer.MIN_VALUE) overflows and stays negative, because MIN_VALUE has no positive counterpart.

open as a page

As an architect, how do you reason about autoboxing performance and the integer-cache range across a large, multi-environment Java system?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

Avoid boxing in hot paths by using primitives, primitive streams, and primitive-specialized collections; never rely on the integer cache (==) for correctness because its range can differ by JVM config. Enforce these with static analysis and benchmarks rather than intuition.

open as a page