jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes passing null as a parameter 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 "passing null as a parameter" Watch "passing null as a parameter" New topic
Author

passing null as a parameter

Vijayalakshmi Kota
Greenhorn

Joined: May 30, 2003
Posts: 1
These r the questions from Abhilash's mockexam site could any one explain why the answers for these questions are :
3A is The code compiles cleanly and shows "String Version"
4A:The code does not compile.
3Q) 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);
}
}
4Q) 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);
}
}
Thanks for any response
kota
[ June 04, 2003: Message edited by: Vijayalakshmi Kota ]
preeti khane
Ranch Hand

Joined: Mar 12, 2003
Posts: 93
hi,
the first question , method overloading is determined by the compiler as the most specific method that a parameter can be passed into...
Object is a superclass of String hence, String is the most specific method parameter

On the 2 question, both string and StringBuffer class are siblings , ie they are sub classes of Object.. so the compiler finds ambiguity in the methods and cannot determine the closest possible fit.....and hence compile error
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
The code in Question 2 failed, not because of the the formal parameter list, but simply because of the use of null in the method call.
In fact, the code in Question 1 is more ambiguous than 2. String and StringBuffer have no direct relationship.
If you where to change the call to:

then the code will compile properly.
The problem in 2 is that the null type can be cast into anything, therefore, it would satisfy both method.
Consider this code:

This code will fail even though class A and class B have no relationship. However, if you were to change the call to

then this would compile properly.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing null as a parameter