Lion Lion - 6 months ago 28
Java Question

Tricky ternary operator in Java - autoboxing

Let's look at the simple Java code in the following snippet:

public class Main {

private int temp() {
return true ? null : 0;
// No compiler error - the compiler allows a return value of null
// in a method signature that returns an int.

private int same() {
if (true) {
return null;
// The same is not possible with if,
// and causes a compile-time error - incompatible types.
} else {
return 0;

public static void main(String[] args) {
Main m = new Main();

In this simplest of Java code, the
method issues no compiler error even though the return type of the function is
, and we are trying to return the value
(through the statement
return true ? null : 0;
). When compiled, this obviously causes the run time exception

However, it appears that the same thing is wrong if we represent the ternary operator with an
statement (as in the
method), which does issue a compile-time error! Why?


The compiler interprets null as a null reference to an Integer, applies the autoboxing/unboxing rules for the conditional operator (as described in the Java Language Specification, 15.25), and moves happily on. This will generate a NullPointerException at run time, which you can confirm by trying it.