Wrapper Classes: Primitives as Objects

Wrapper Classes: Primitives as Objects in Java: A distribution depot runs an automated sortation line that only moves totes -- plastic crates with a scanned…

The Analogy: The Parcelling Bench At A Distribution Depot

A distribution depot runs an automated sortation line that only moves totes -- plastic crates with a scanned barcode. Loose steel parts cannot ride the line at all; the rollers and scanners have nothing to grip or read. So at goods-inwards there is a parcelling bench, and every loose part that needs to travel the line is placed into a standard tote first. The part is the same part it always was; it is just wrapped in something the line can handle. A primitive int is that loose part. An Integer is the tote around it. The collections and generics of Java are the sortation line: they move objects, never bare primitives, so a primitive that needs to go there must be boxed first.

The bench is mostly automatic. Drop a loose part where the line expects a tote and the bench boxes it without being asked; lift a part off the line into a slot that expects a loose part and the bench tips it out of its tote. That automatic boxing and unboxing is a convenience, and most of the time you never see it happen. But the tote is not free -- it takes shelf space, it has to be fetched, and tipping a part out of it takes a moment. A line that boxes and unboxes a million parts pays for a million totes.

The depot keeps one shrewd optimisation. For the commonest small part numbers it maintains a shelf of pre-labelled totes and reuses them rather than fetching a fresh crate each time. Ask the bench for part number 100 twice and you may well be handed the very same tote both times -- physically one crate. But ask for part number 200, which is outside the small-parts shelf, and you get a freshly fetched tote each time, two distinct crates that merely hold equal parts. This matters the instant anyone compares totes by asking "is this the same crate?" instead of "do these crates hold the same part?"

The failure mode is a clerk who checks whether two orders are for the same quantity by comparing the totes themselves -- same crate or not -- rather than tipping both out and comparing the parts. In testing every quantity is small, lands on the reused-tote shelf, and the crate-identity check is accidentally right. In production a quantity of 200 gets a fresh crate each time, the identity check says "different" for two genuinely identical orders, and a duplicate-order guard silently stops firing. Nothing errored; the depot just compared the wrong thing, and only for the large quantities the tests never used.


Syntax or Core Structure

public class Bench {
    public static void main(String[] args) {
        int loose = 42;
        Integer boxed = loose;          // autoboxing
        int back = boxed;               // auto-unboxing

        Integer parsed = Integer.parseInt("123");
        Integer valued = Integer.valueOf(7);

        System.out.println("boxed:   " + boxed);
        System.out.println("back:    " + back);
        System.out.println("parsed:  " + parsed);
        System.out.println("valued:  " + valued);
        System.out.println("max:     " + Integer.MAX_VALUE);
        System.out.println("bits:    " + Integer.SIZE);
        System.out.println("sum:     " + Integer.sum(back, valued));
        System.out.println("hex:     " + Integer.toHexString(255));
    }
}

Output:

boxed:   42
back:    42
parsed:  123
valued:  7
max:     2147483647
bits:    32
sum:     49
hex:     ff

Assigning an int to an Integer boxes it; assigning it back unboxes it. parseInt reads a numeric string into a value, and the wrapper type carries constants like MAX_VALUE and utilities like sum and toHexString that a bare int has nowhere to hold.


Technical Depth: What Boxing Costs, Why == Betrays You, And How null Unboxing Throws

The Eight Wrappers And Their Primitives

Every primitive has exactly one wrapper class, and each wrapper is immutable and final -- once created, the value inside never changes, and reassigning a wrapper variable swaps in a different object rather than mutating the old one.

PrimitiveWrapperParse methodCached range
intIntegerparseInt-128 to 127
longLongparseLong-128 to 127
shortShortparseShort-128 to 127
byteByteparseByteall values
charCharacternone0 to 127
booleanBooleanparseBooleanboth values
floatFloatparseFloatnone
doubleDoubleparseDoublenone

The integral wrappers, Character, and Boolean maintain caches; Float and Double never cache because the range of floating values is too large for a fixed table to help.

Autoboxing And Its Hidden Cost

Autoboxing is the compiler inserting Integer.valueOf where a primitive meets an object context, and auto-unboxing is it inserting intValue() where an object meets a primitive context. The convenience hides a real cost: each box is an object allocation, and a loop that accumulates into a wrapper reboxes on every iteration.

public class Cost {
    public static void main(String[] args) {
        long start = 0;

        // Accidental boxing: Long, not long, reboxes each step.
        Long boxedSum = 0L;
        for (int i = 1; i <= 1000; i++) {
            boxedSum += i;        // unbox, add, rebox -- every step
        }

        long primitiveSum = 0L;
        for (int i = 1; i <= 1000; i++) {
            primitiveSum += i;    // no allocation at all
        }

        System.out.println("boxed:   " + boxedSum);
        System.out.println("prim:    " + primitiveSum);
        System.out.println("equal:   "
            + (boxedSum.longValue() == primitiveSum));
    }
}

Output:

boxed:   500500
prim:    500500
equal:   true

Both loops compute the same total, but the Long accumulator unboxes, adds, and reboxes on every one of the thousand iterations, allocating a fresh Long each time, while the long accumulator touches no heap at all. Declaring an accumulator as a wrapper by accident is one of the commonest silent performance leaks in Java.

Why == Betrays You On Wrappers

On primitives == compares values. On wrappers == compares references -- whether the two operands are the same object -- and equals compares the wrapped values. The cache makes this treacherous, because small boxed values may share an object and compare == true, while equal large values do not.

ComparisonBoth wrappersOne primitiveWhat it tests
a == bReference identityUnboxes, compares valuesSame object, or equal value if unboxed
a.equals(b)Wrapped valuesN/A (primitive has no method)Equal value, always
a < bBoth unboxUnboxes the wrapperOrdering of values

The only == on wrappers that always reflects value is the mixed case where one side is a primitive and forces an unbox; between two wrappers, == is an identity test and equals is the value test.

public class Identity {
    public static void main(String[] args) {
        Integer a = 100, b = 100;      // cached, same object
        Integer c = 200, d = 200;      // fresh objects each

        System.out.println("a==b:    " + (a == b));
        System.out.println("c==d:    " + (c == d));
        System.out.println("a.eq b:  " + a.equals(b));
        System.out.println("c.eq d:  " + c.equals(d));

        int e = 200;
        System.out.println("c==e:    " + (c == e));   // unboxes c
    }
}

Output:

a==b:    true
c==d:    false
a.eq b:  true
c.eq d:  true
c==e:    true

The value 100 lands in the cache, so a and b are the same object and == is true; 200 is outside the cache, so c and d are distinct objects and == is false even though the values match. equals reports true in both cases because it compares values. The last line is the escape hatch: comparing a wrapper with a primitive unboxes the wrapper, so c == e compares values and is true.

null Unboxing Throws

A wrapper reference can be null; a primitive cannot. When an auto-unbox tries to read a value out of a null wrapper it throws NullPointerException, and because the unbox is invisible in the source the crash lands on an innocent-looking line -- an arithmetic expression, a comparison, an assignment to an int.

import java.util.HashMap;
import java.util.Map;

public class Empty {
    static int quantity(Map<String, Integer> stock, String part) {
        boolean threw = false;
        try {
            int q = stock.get(part);   // get returns null; unbox throws
            return q;
        } catch (NullPointerException e) {
            threw = true;
        }
        return threw ? -1 : 0;
    }

    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("bolt", 40);

        System.out.println("bolt:    " + quantity(stock, "bolt"));
        System.out.println("washer:  " + quantity(stock, "washer"));
        System.out.println("safe:    "
            + stock.getOrDefault("washer", 0));
    }
}

Output:

bolt:    40
washer:  -1
safe:    0

The missing key returns null from get, and assigning that null to an int unboxes it, throwing NullPointerException -- reported here as -1. The fix is to stay in wrapper space and check for null, or to use getOrDefault so a primitive default is supplied before any unbox happens. See [[hashmap]] for why get returns null on a missing key.

Parsing, valueOf, And When To Use Which

The wrapper classes are also the front door for turning text into numbers. Integer.parseInt(s) returns a primitive int; Integer.valueOf(s) returns an Integer and consults the cache. Prefer parseInt when you want a primitive and valueOf when you genuinely want a boxed value, and never chain new Integer(...), which is deprecated for removal precisely because it bypasses the cache and always allocates.


Real World Example: A Duplicate-Order Guard That Compared Totes

An order service flags a suspected duplicate when a new order's quantity matches the previous order's quantity for the same customer. The previous quantity is held as an Integer because it comes out of a nullable database column, and the author compared the two quantities with ==. The unit tests used small quantities -- 5, 10, 20 -- all inside the Integer cache, so the boxed values shared objects and == was accidentally correct. The bug only appears above 127.

import java.util.Locale;

public class OrderGuard {

    // Broken: reference comparison on boxed quantities.
    static String brokenDuplicate(Integer previous, Integer current) {
        boolean flagged = previous != null && previous == current;
        return flagged ? "DUPLICATE" : "DISTINCT ";
    }

    // Fixed: value comparison via equals, null-safe.
    static String fixedDuplicate(Integer previous, Integer current) {
        boolean flagged = previous != null
            && previous.equals(current);
        return flagged ? "DUPLICATE" : "DISTINCT ";
    }

    static void check(int qty) {
        Integer previous = qty;   // fresh box
        Integer current = qty;    // fresh box
        System.out.println(String.format(Locale.ROOT,
            "qty %4d  broken %s  fixed %s",
            qty,
            brokenDuplicate(previous, current),
            fixedDuplicate(previous, current)));
    }

    public static void main(String[] args) {
        check(20);
        check(200);
    }
}

Output:

qty   20  broken DUPLICATE  fixed DUPLICATE
qty  200  broken DISTINCT   fixed DUPLICATE

At quantity 20 both versions agree, because 20 is inside the Integer cache: the two boxes are the same object, so == is true and matches equals. At quantity 200 the versions diverge. The two boxes are distinct objects, == is false, and the broken guard declares two identical orders distinct -- exactly the duplicate it exists to catch, waved through. The fixed guard uses equals, compares the wrapped values, and flags both.

The trap is that the broken code is not merely wrong, it is wrong only sometimes, and never in the region the tests explored. Small quantities live on the cache shelf and share a tote, so reference comparison is accidentally right for them; the failure is latent until a real order crosses 127. A test suite full of small fixtures can give total confidence in code that is broken for most of its real inputs. This is the defining hazard of wrapper identity: the cache makes == behave like value comparison for exactly the values a developer is most likely to type into a test.

The correct model is that a wrapper is an object, and two objects are compared for sameness with equals, never ==, unless you specifically mean "the same instance". Reserve == for null checks and for the deliberate case where one side is a primitive and you want the unbox. Everywhere else on wrappers, reach for equals.

The genuine limit worth naming is that the cache range is an implementation guarantee for -128 to 127 only; the JVM may cache a wider range if configured, so code that relies on == being false above 127 is as broken as code that relies on it being true below 128. The design flaw here was storing a quantity as a nullable Integer and then comparing it as if it were an int -- mixing the object and primitive mental models in a single expression. Either keep it boxed and use equals, or unbox both sides to int after a null check and use == on primitives; do not straddle the two.


Common Mistakes

  1. Comparing wrappers with ==. It compares references, so equal values above 127 test unequal while cached small values test equal. Use equals for value comparison, or unbox to primitives first.
  1. Unboxing a possibly-null wrapper. Assigning a null Integer to an int, or using it in arithmetic, throws NullPointerException on an invisible unbox. Null-check first or use getOrDefault.
  1. Declaring an accumulator as a wrapper. A Long or Integer loop counter reboxes on every iteration, allocating needlessly. Use the primitive type for loop variables and accumulators.
  1. Assuming the cache range is fixed at 127. The guaranteed range is -128 to 127, but the upper bound can be raised by a JVM flag. Never write logic that depends on == results for boxed values at all.
  1. Calling new Integer(...). The constructors are deprecated for removal; they always allocate and bypass the cache. Use Integer.valueOf for a wrapper or parseInt for a primitive.
  1. Confusing parseInt with valueOf. parseInt returns a primitive int; valueOf returns a boxed Integer and consults the cache. Pick by whether you want a primitive or an object.
  1. Ignoring NumberFormatException from parsing. parseInt on non-numeric or malformed text throws at runtime. Validate or catch when the string is external or untrusted.
  1. Autoboxing in a hot loop unknowingly. A method typed to take Object or a wrapper boxes every primitive argument. Watch generic collections and varargs in performance-sensitive code.
  1. Using a wrapper where a primitive would do. Fields and locals typed Integer instead of int invite null, add allocation, and open the == trap for no benefit. Default to primitives; use wrappers only when nullability or an object context requires them.

Best Practices

  • Compare wrapper values with equals, never ==. Reserve == on a wrapper for a null check or a deliberate identity test; for value equality equals is the only correct choice.
  • Default to primitives; box only when required. Reach for a wrapper when you need nullability, a collection element, or a generic type argument, and stay on int, long, and double everywhere else.
  • Null-check before an unbox, or use getOrDefault. Treat any wrapper that might be null as a landmine for the invisible unbox, and supply a primitive default before the value is read.
  • Type accumulators and loop counters as primitives. A wrapper accumulator reboxes every iteration; a primitive one touches no heap and runs measurably faster in tight loops.
  • Use Integer.valueOf for boxing and parseInt for primitives. They express intent and use the cache; never call the deprecated wrapper constructors.
  • Catch or validate NumberFormatException on external input. Any parse of user-supplied or file-supplied text can fail; handle it rather than letting it crash a request.
  • Prefer the static utilities the wrappers expose. Integer.compare, Integer.sum, Integer.parseInt, and Integer.toHexString are correct and clear where hand-rolled equivalents invite bugs.
  • Keep a value on one side of the object-primitive line. Decide whether a quantity is a nullable Integer or a plain int and treat it consistently; mixing the two models in one expression is where the == trap lives.

Practice Exercises

  1. The Order Above 127. Write a method that reports whether two Integer quantities are equal, first using ==. Test it with 50 and with 200 and observe that only the large case is wrong. Rewrite it with equals (guarding null first) and confirm both cases are correct, explaining in one sentence why the small case passed with the broken version.
  1. The Empty Tote. Build a Map<String, Integer> of stock levels and write int level(map, part) that unboxes map.get(part) directly, then call it for a present and an absent part; catch the NullPointerException from the absent one. Rewrite level to return a primitive safely with getOrDefault, and explain where the invisible unbox was happening.
  1. The Rebox Tax. Sum the integers 1 to one million twice, once into a long accumulator and once into a Long, and print both totals to confirm they match. Explain in two sentences what the Long version does on every iteration that the long version does not, and why that makes it the slower of the two.