Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come method returning boolean still compiles when return uses a ternary operator? [duplicate]

Tags:

java

How come this code compiles? I would have expected the compiler to complain about a "Type mismatch: cannot convert from null to boolean" but it doesn't. It just fails with a NullPointerException at runtime.

public static void main(String[] args) throws Exception {
    System.out.println("this throws a NPE: " + whyIsThisPossible(1, 2));
}

private static boolean whyIsThisPossible(int a, int b) {
    return a + b == 2 ? true : null;
}

Exception in thread "main" java.lang.NullPointerException
at FunkyMethodTest.whyIsThisPossible(FunkyMethodTest.java:10)
at FunkyMethodTest.main(FunkyMethodTest.java:5)*
like image 799
Mike Avatar asked Jan 31 '26 21:01

Mike


1 Answers

Java considers the type of ternary expression to be boolean. The compiler treats null as Boolean, i.e. the result of applying a boxing conversion to the primitive type of boolean.

Here is the relevant portion of the language specification:

15.25 The type of a conditional expression is determined as follows:

...

  • 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.

Language specification states that the boxing/unboxing conversion is applied when necessary to the operand chosen by the condition of the expression. That is what triggers the exception when the code tries to unbox a boolean from null.

like image 51
Sergey Kalinichenko Avatar answered Feb 02 '26 12:02

Sergey Kalinichenko