Search code examples
javacompiler-errorscompilationjavac

How can this Java code compile without error?


Can someone explain why does this Java code compile?

public class Main {
     public static void main(String []args){
        System.out.println(foo(true));
        System.out.println(foo(false));
     }

     public static boolean foo(boolean value) {
         // this should make the compiler say something, at least complain a bit...
         return value ? true : null;
     }
}

Solution

  • As Oliver said in the comments, the reason this compiles is autoboxing.

    The null can be autoboxed into a Boolean which can be autounboxed to a boolean, making the compiler happy. At runtime the autoboxing works, but when it's unboxed to a boolean it will throw a NullPointerException.