Video in progress

Strong Junior ☕ Core Java

Why does this code throw a NullPointerException?

Map<String, Integer> bonus = new HashMap<>();
boolean vip = true;
Integer points = vip ? bonus.get("ali") : 0;

One side of the ternary operator is the primitive int (0), so the whole expression stays an int and the Integer side gets unboxed. When map.get(...) returns null, the unboxing throws an NPE.

📖 Answer

The expected result was points = null. But by a Java rule, if the two sides of a ternary are Integer and int, the result type is int. So the compiler generates code like this:

Integer points = Integer.valueOf(vip ? bonus.get("ali").intValue() : 0);

bonus.get("ali") is null, and .intValue() throws an NPE.

This bug is very misleading: the stack trace points to this line, but there's no visible method call on a dot in it.

Ways to fix it:

Integer points = vip ? bonus.get("ali") : Integer.valueOf(0); // both sides are Integer
int points2 = vip ? bonus.getOrDefault("ali", 0) : 0;          // can't be null

The same problem shows up in switch expressions and when Boolean/boolean are mixed. The rule: don't mix a wrapper class and a primitive in one expression, or check the value that might be null beforehand.