Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...