Search code examples
javanullsystemprintlnsystem.out

Why does `System.out.println(null);` give "The method println(char[]) is ambiguous for the type PrintStream error"?


I am using the code:

System.out.println(null);

It is showing the error:

The method println(char[]) is ambiguous for the type PrintStream

Why doesn't null represent Object?


Solution

  • There are 3 println methods in PrintStream that accept a reference type - println(char x[]), println(String x), println(Object x).

    When you pass null, all 3 are applicable. The method overloading rules prefer the method with the most specific argument types, so println(Object x) is not chosen.

    Then the compiler can't choose between the first two - println(char x[]) & println(String x) - since String is not more specific than char[] and vice versa.

    If you want a specific method to be chosen, cast the null to the required type.

    For example :

    System.out.println((String)null);