Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    Wrapper Classes and Autoboxing

    Each primitive type has a wrapper class that holds one value as an object:

    Chapter 8 of 105 min read

    The Plain Picture#

    Some shipping services only accept boxes — they won't take a loose apple. So you put the apple in a small box. The box costs extra space and time to pack and unpack, and an empty box (with no apple) is possible too.

    The Real Names#

    • Each primitive type has a wrapper class that holds one value as an object:

    PrimitiveWrapper
    intInteger
    longLong
    doubleDouble
    booleanBoolean
    charCharacter
    byte, short, floatByte, Short, Float
    • Why wrappers exist: Java's collections (ArrayList, HashMap — Collections, From the Inside) and generics (Exceptions and Generics) can only hold objects, not primitives. List<int> is illegal; List<Integer> is fine.

    • Autoboxing — Java automatically wraps a primitive when an object is needed (Integer x = 5;). Unboxing — it automatically unwraps when a primitive is needed (int y = x;).

    Under the Hood#

    The Integer cache trap#

    Java
    Integer x1 = 127,
        y1 = 127,
        x2 = 128,
        y2 = 128;
    
    System.out.println((x1 == y1) + " " + (x2 == y2) + " " + x2.equals(y2));
    // true false true

    Autoboxing calls Integer.valueOf, which keeps a cache of Integer objects for −128 to 127. So boxing 127 twice gives the same cached object (== true), but 128 creates two separate objects (== false). It's the String pool story again (Ch 6): == compares references.

    In DSA this bites when comparing values from collections: map.get(a) == map.get(b) works in small tests (small numbers) and fails on large ones. Compare wrapper objects with .equals, or unbox to primitives first (int v = map.get(a);).

    Unboxing null → NullPointerException#

    A wrapper can be null (the empty box). Unboxing null throws:

    Java
    Integer maybe = null;
    
    int v = maybe; // NullPointerException when unboxing null

    Classic cause: int count = map.get(key); when the key isn't in the map (get returns null). Use map.getOrDefault(key, 0) (Collections, From the Inside).

    The cost of boxing — measured#

    One million numbers stored two ways, measured on this Mac:

    Output
    int[]:                3 MB
    ArrayList<Integer>:  21 MB

    Each boxed Integer is a separate heap object with a header (about 16 bytes), plus a 4–8 byte reference to it in the list — versus 4 bytes per int in an array, packed side by side for the cache (How Computers Work Ch 6). For large numeric data in DSA, prefer primitive arrays.

    Character helpers — used constantly in string problems#

    Java
    Character.isDigit('7')          // true
    Character.isLetter('a')         // true
    Character.isLetterOrDigit('_')  // false   ← "alphanumeric" checks, e.g. valid palindrome problems
    Character.toLowerCase('Q')      // 'q'
    Character.getNumericValue('7')  // 7
    '7' - '0'                       // 7       ← the usual quick way (01_java_basics.md Ch 3)

    And the parsing helpers from Java Basics Ch 4 are static methods on wrappers: Integer.parseInt, Long.parseLong, Integer.MAX_VALUE, Integer.toBinaryString(5) → "101".

    Gotchas

    • == on Integer, Long etc. — same trap as strings. Use .equals or unbox.

    • Long l = 5; doesn't compile (5 is an int, which can't be boxed to Long); write 5L.

    • list.remove(1) on a List<Integer> removes the element at index 1, not the value 1 — use list.remove(Integer.valueOf(1)) for the value. (Overloading, Java Basics Ch 7, picks remove(int index) because an exact int match beats boxing.)

    Check yourself

    5 questions
    1

    Why do wrapper classes exist?

    Show answer

    Collections and generics can only hold objects, so primitives need object versions.

    2

    What are autoboxing and unboxing?

    Show answer

    Automatic conversion from primitive to wrapper object and back.

    3

    Why is Integer a = 1000, b = 1000; a == b false, but true for 100?

    Show answer

    Integer.valueOf caches −128..127, so 100 gives the same cached object; 1000 gives two separate objects, and == compares references.

    4

    What happens with int c = map.get("missing");?

    Show answer

    get returns null, and unboxing null into int throws a NullPointerException.

    5

    Why is int[] better than ArrayList<Integer> for a million numbers?

    Show answer

    Far less memory (4 bytes per element vs a whole object plus a reference) and better cache behaviour.