Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java compiler allow casting null to primitive type in ternary operator

This small program throws NullPointerException at the line of ternary operator:

public class Main {
    int someMethod() {
        return (true ? null : 0);
    }

    public static void main(String[] args)  {
        Main obj= new Main();
        obj.someMethod();
    }
}

I understand the reason is null cannot be casted to int.

However, the question is why does Java compiler allow this kind of code passed, while something likes below will cause compile-time error:

int i = null; //Error: incompatible types: <nulltype> cannot be converted to int
like image 306
alex chen Avatar asked May 10 '26 01:05

alex chen


1 Answers

By Java Language Specification - Conditional Operator, Java will evaluate the conditional expression at run-time, not compile-time. That's why the error is not detected during compile-time:

At run time, the first operand expression of the conditional expression is evaluated first. The resulting boolean value is then used to choose either the second or the third operand expression.

So in your case:

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

imaging true is a method containing complicated logic, and it makes sense if Java evaluate the 1st operand (in this case is true) at run-time. Then, based on the rule:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

Since 3rd operand 0 is primitive type (T), the type of the expression would be T type (int). So, unboxing a null reference to int will result in NPE.

like image 67
tonyhoan Avatar answered May 11 '26 16:05

tonyhoan



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!