• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between Null String and Null Object  RSS feed

 
Roshan Cherian
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please refer to the code snippet

class Test{
public static void getString(Object obj){
System.out.println( "object " + obj );
}

public static void getString(String obj){
System.out.println( "String " + obj );
}
public static void main(String args[])
{
new Test().getString(null);
}
}

While I ran this I am getting the output String null.Why is it so??Why it takes the 2nd method getString(String obj)??
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, I would re-write it to stop my compiler from complaining about static access to an instance:


You want to read up on overload resolution.

When you finally get down to the third rule (which this question does), the compiler picks the most specific invocation it possibly can. Since String is more specific than Object, and null can be either, String is chosen.
[ November 26, 2007: Message edited by: Bill Shirley ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. A single name isn't enough. You can change your display name here. Thanks!

Also, we have many forums here at JavaRanch; this one is for discussing the Enterprise Java Beans APIs, which doesn't seem to pertain to your question. I'll move this to our Beginner's Java forum, where it is on-topic.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!