Java returns null for primitive in ternary
The following (logically) 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. I don't understand that the following is allowed:
public int myMethod(MyObject input) {
return input == null ? null : 1;
}
Why? Should it be easy for the compiler to admit it, or am I missing an important point here?
(And, of course, if the ternary operator ends with a "null branch", then it's NPE, what else? :))
source to share
The type of a ternary conditional operator is determined by the types of its second and third operands.
When
input == null ? null : 1
a type Integer
to which both null
and 1
.
The compiler allows your method to return Integer
as it can be automatically unpacked into int
, so it matches the type int
return << 27>.
The fact that your specific code might throw NullPointerException
is not something the compiler might detect.
source to share