Java autoboxing and ternary operator madness

Ternary expressions, like any expression, have a type that is determined by the compiler. If the two sides of the ternary expression have what looks like different types, then the compiler will try and find a common base type using the least ambiguous of the two options. In your case, the -1 is least ambiguous, and so the type of the ternary expression is int. Sadly, the compiler doesn’t use type inference based on the receiving variable.

The expression rsrqs.get(boxedPci.toString()) is then evaluated and forced into type int to match the ternary expression, but because it’s null it throws the NPE.

By boxing the -1, the value of the ternary expression is Integer, and so you’re null-safe.

Leave a Comment