Common Pitfalls

Comparing Wrappers with ==

Example

== on wrappers compares references. Java caches Integer values from -128 to 127, so small numbers seem to work and big ones fail. Always use equals().

public class Main {
    public static void main(String[] args) {
        Integer a = 100, b = 100;
        Integer c = 1000, d = 1000;
        System.out.println("100 == 100   : " + (a == b));      // cached, same object
        System.out.println("1000 == 1000 : " + (c == d));      // different objects
        System.out.println("equals       : " + c.equals(d));   // correct
        System.out.println("intValue ==  : " + (c.intValue() == d.intValue()));
    }
}

Output

100 == 100   : true
1000 == 1000 : false
equals       : true
intValue ==  : true

Unboxing null

Example

Unboxing a null wrapper throws NullPointerException. This often happens with Map.get() for a missing key.

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

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

        int apples = stock.get("apple");
        System.out.println("Apples: " + apples);

        int safe = stock.getOrDefault("mango", 0);
        System.out.println("Mangoes (safe): " + safe);

        int mangoes = stock.get("mango");   // null -> int: NullPointerException
        System.out.println(mangoes);
    }
}

Output

Apples: 50
Mangoes (safe): 0
Exception: java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null

Practice

Exercise: What does this print? Long x = 127L; Long y = 127L; System.out.println(x == y); Long p = 128L; Long q = 128L; System.out.println(p == q);

Show answer
true    // Long also caches -128..127
false   // 128 is outside the cache, different objects
// Use x.equals(y) to compare values.