• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

give explanation

 
vinod kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai
iam a biginner i java ..please give an explanation for the following ..

class Test{
public void method(Object o){
System.out.println("in object");
}
public void method(String s){
System.out.println("in String");
}

public static void main(String []args){

Test t=new Test();
t.method(null)
}
}

when executing iam getting the out put in String

Why ?
why it is not going to the first method ?
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In some cases, a null reference of type String is treated as the String literal "null" so the method with string argument is called.

Check this Thread .
 
vinod kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but srini as per the link u send..it is happening during concatenation ..but why in this case..?
 
Yosi Hendarsjah
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Srini's answer is wrong. The method that has String as the parameter is invoked because String is more specific (String is a subclass of Object). If you modify the second method, change the paramater type to Integer,

it will print "in Integer".

For more information, read this excerpt from Java Language Specification.
[ March 04, 2005: Message edited by: Yosi Hendarsjah ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yosi is correct. A null reference can be converted to any object type, so a null argument will invoke the method with the most specific argument type.
 
vinod kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u for the reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic