aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Pass a Null as parameter?! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Pass a Null as parameter?!" Watch "Pass a Null as parameter?!" New topic
Author

Pass a Null as parameter?!

Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
Read the code below. Will be the result of attempting to compile and run the code below.
public class AQuestion
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}
}
Answers
1.The code does not compile.
2.The code compiles cleanly and shows "Object Version".
3.The code compiles cleanly and shows "String Version"
4.The code throws an Exception at Runtime.
Can someone please explain to me why the output is "String Version" / Answer 2
I am very confuse!!
Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
Sorry, the answer should be Answer 3.
Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
Here is another similar question:
Read the code below. Will be the result of attempting to compile and run the code below.
public class AQuestion
{
public void method(StringBuffer sb)
{
System.out.println("StringBuffer Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}
}
Answers
1.The code does not compile.
2.The code compiles cleanly and shows "StringBuffer Version".
3.The code compiles cleanly and shows "String Version"
4.The code throws an Exception at Runtime.
Now, this time is Answer 1!! :-(
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
When you invoke overloaded methods with the null argument, the compiler resolves the method invocation by taking the method with the most specific argument type. In your first example, String is more specific than Object and that's why the method with the String argument is executed.
In your second example, there is no method being more specific than the other since String and StringBuffer are not related in any way, thus resulting in a compilation error.
You may want to read the following JLS section:
15.12.2.2 Choose the Most Specific Method
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Pass a Null as parameter?!