Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing null as a parameter

 
Vijayalakshmi Kota
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic