Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java return null for primitive in ternary [duplicate]

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

like image 383
D. Kovács Avatar asked May 05 '26 03:05

D. Kovács


1 Answers

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.

like image 138
Eran Avatar answered May 07 '26 16:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!