File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why this outout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why this outout" Watch "why this outout" New topic

why this outout

Sireesha Mullapudi
Ranch Hand

Joined: Jun 26, 2006
Posts: 74

Why the following code is not giving compile time error

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10032

Hi Lakshmi,

Why do you think that it should give a compile time error?? The method method(null) matches the string version and prints string as o/p. If you remove the static method that takes String as argument, it prints object as the O/P. It's a good question. Can anyone please explain this behaviour.

Jothi Shankar Kumar. S

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
anvesh charuvaka

Joined: Sep 25, 2006
Posts: 11

The null Literal can be cast into any type of Object Reference.
So any one of the given method()'s can be called but the compiler tries to choose the most specific one.

Now the null matches the call for method(Object )
then it also matches the call for method(String )

since the string version is more specific the call is made to the method(String ) version.

But if you overload the method with Integer
metod(Integer ) then the complier does not know which one to call because
The String version is as specific as Integer version so the compiler shouts that the call is "AMBIGUOUS"
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3635
I can almost hear someone say, "how do you know X is more specific than Y?"

Simple answer is, if X extends Y directly or indirectly, X is more specfic than Y. If there is no direct or indirect inheritance relationship between X and Y, both are equally specific.

So Integer is more specific than Number and Number is more specific than Object. But String and Integer(or Number) are equally specific.

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi all,

this ambiguity can be seen for interfaces as well:

This code produces:
class A

but if you delete the method // for A's
it is ambigous and the line foo(a); in main cannot compile.
Same would be true for foo(null);


all events occur in real time
I agree. Here's the link:
subject: why this outout
jQuery in Action, 3rd edition