Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes give explanation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "give explanation" Watch "give explanation" New topic

give explanation

vinod kumar

Joined: Jan 24, 2005
Posts: 15
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();

when executing iam getting the out put in String

Why ?
why it is not going to the first method ?
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
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 .

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
vinod kumar

Joined: Jan 24, 2005
Posts: 15
but srini as per the link u is happening during concatenation ..but why in this case..?
Yosi Hendarsjah
Ranch Hand

Joined: Oct 02, 2003
Posts: 166
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

Joined: Aug 31, 2004
Posts: 11343

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.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
vinod kumar

Joined: Jan 24, 2005
Posts: 15
thank u for the reply.
I agree. Here's the link:
subject: give explanation
It's not a secret anymore!