Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 775
Kannan Thangadurai Avatar asked Mar 31 '16 05:03

Kannan Thangadurai


1 Answers

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); 
like image 200
Eran Avatar answered Nov 22 '22 09:11

Eran