Java return null for primitive in ternary [duplica

2019-02-19 00:43发布

问题:

This question already has an answer here:

  • Returning null as an int permitted with ternary operator but not if statement 8 answers

The following (logically) is a compile-time error:

public int myMethod(MyObject input) {
   if (input == null) {
     return null; // compiler says I cannot return null for primitive type
   } else {
     return 1;
   }
}

So far so good. What I don't understand, that the following is allowed:

public int myMethod(MyObject input) {
   return input == null ? null : 1;
}

Why? Recognising this should be straightforward for the compiler, or do I miss some crucial point here?

(And of course if in the ternary operator one ends up on the "null-branch", then it's a NPE, what else? :))

回答1:

The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.

In the case of

input == null ? null : 1

the type is Integer, which can be assigned both null and 1.

The compiler allows your method to return an Integer since it can be auto-unboxed into an int, so it fit the int return type of myMethod.

The fact that your specific code may throw a NullPointerException is not something the compiler can detect.