Search code examples
javacompiler-errorsoverloadingconditional-operatorambiguous

Puzzling "reference to println is ambiguous" compilation error


If I compile and run the following class (with Java SE 7, if that matters),

class Foo {

    public static void main(String[] args) {
        System.out.println(true ? null : 42);
        // System.out.println(null);
    }
}

I get the following output

null

So far, so good. However, if I uncomment the second statement in main, I get a compilation error:

Foo.java:5: error: reference to println is ambiguous, both method println(char[]) in PrintStream and method println(String) in PrintStream match

      System.out.println(null);
                  ^

Why does the Java compiler throw this error if the argument of System.out.println is null, but doesn't if the argument is true ? null : 42?


Solution

  • The type of the expression true ? null : 42 is Integer therefore it is unambiguous that System.println(Object) should be called.

    If you call System.println(null) there are multiple candidate methods and the compiler can't decide which one to take.