Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Boxing, unboxing and wrapper cache identity

Boxing converts a primitive value to a wrapper object, while unboxing retrieves its value. Learn how == differs from equals and why null and shared wrapper instances can cause surprises.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Integer boxed = 42;
int primitive = boxed;
boolean sameReference = boxed == anotherBoxed;
boolean sameValue = boxed.equals(anotherBoxed);

Boxing converts a primitive value to its corresponding wrapper type, for example int → Integer; unboxing reverses this. Integer boxed = 42; and int primitive = boxed; illustrate automatic conversions. Unboxing null throws NullPointerException.

For two Integer references, == tests object identity, not numeric value. For a non-null reference x, x.equals(y) checks whether y is an Integer with the same value. In contrast, x == 1000 unboxes and compares numbers; x == null does not perform that unboxing.

JLS §5.1.7 guarantees that repeatedly boxing the same value obtained from a constant expression yields references to the same object in these cases: boolean values true and false, char values from 0 to 127 inclusive, and short, int, or long values from -128 to 127 inclusive. This rule does not list byte. Outside that guarantee, assume neither shared nor distinct objects. Separately, the Integer.valueOf(int) contract guarantees caching of -128–127 and permits a wider range.

The example deliberately does not print x == y: for 1000, the result would depend on object sharing. Integer is a value-based class; do not use its instances as synchronization locks.

Reference identifiers covered by this entry: Boxing, unboxing and wrapper cache identity.

Examples

public class BoxingDemo {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        int value = a;
        Integer x = 1000;
        Integer y = 1000;

        System.out.println(a == b);
        System.out.println(value);
        System.out.println(x.equals(y));
        System.out.println(x == 1000);

        Integer missing = null;
        try {
            int number = missing;
            System.out.println(number);
        } catch (NullPointerException ex) {
            System.out.println("NullPointerException");
        }
    }
}

Result

true
127
true
true
NullPointerException

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources