Why is compilation allowed when the expected return type mismatch?

int fun(){ return (true?null:0); } 

Here, explicitly null does not refer to the int type, which is allowed to return and compile-time errors

+4
source share
2 answers

Wrapper class. For ex

 Integer integ = null; 

You are allowed to do

 int fun(){ return (true?integ:0); } 

Auto-boxing and unpacking. But when you run this code, you will encounter NPE, since the runtime will try to convert the null integer to the corresponding primitive.

+2
source

There is no inconsistent type. Your example can be simplified to

 public int foo() { return true ? 0 : null; } 

Ternar will automatically put 0 in type Integer , which automatically returns back to int . Since a Integer can also be null , both expressions in ternary then have the same type.

In null branches, a NullPointerException will be thrown. See for yourself by changing true to false in my example

In my opinion, this is one of the drawbacks of Java, which comes from the retention of simple old data types, and the rules of type promotion in triple form are especially harmful.

+2
source

All Articles