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? :))