Though this is well known by Java veterans, a brief recap can’t hurt: There several ways that Java’s autoboxing can bite you on the ass when you combine it with the ternary operator.
Here’s the classic ternary/autoboxing interaction that programmers don’t expect:
Integer n = null;
// we only want to increment n if it's not null
n = n == null ? n : n + 1;
Bang, this will raise a NullPointerException when a is null. Why? Because adding 1 to n will result in a primitive int requiring the JVM to coerce the other side of the ternary operator into a primitive (which fails because it’s null).
If the above convinces you that autoboxing doesn’t play nicely with the ternary operator, you can try avoiding it:
// okay so autoboxing is tricky, don't use it then
Object d = true ? new Integer(1) : new Double(1.0);
Here d gets assigned an instance of Double equal to 1.0. Maybe not what you expected; autoboxing even interferes here.
Here’s a final one, which isn’t actually a side-effect of autoboxing, though it’s more likely to occur in scenarios where autoboxing is used. It begins with a simple error:
Integer n = 1;
//... n was actually a counter retrieved from a map ...
n = n == null ? 1 : n++;
The resulting value of n? 1 of course! At first glance, this looks like regular code for simply initializing/maintaining an Integer counter. Then you realize that the post-increment operator is being used instead of a basic addition. The nasty thing here is that the code will compile and run but will never count beyond 1. This is because the value returned from the ++ operator is the value of the variable before it’s applied, and the assignment it performs is overwritten by the result of the ternary operator.
It’s remarkable that after this many years of computer science we still have mainstream computer languages that obfuscate counting.