• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing Null as argument  RSS feed

 
Manish Khurana
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
This one compiles cleanly and prints
String Version

Is it beacuse that null can be passed around where objects are expected and compiler dosent give null ponter exception unless we dig deeper into null.

I thought it had to do with null being fitted into more specific String rather than Object.
[ January 26, 2008: Message edited by: Manish Khurana ]
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right on both parts. Null references can be passed around w/o problems as long as they aren't dereferenced, and the String version is selected because it is more specific than the Object version.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will fail however if you create a method "public void method(Integer s)", or any other class, because then the compiler can't make a choice for you. In that case, cast the null value:
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please have a look at Which is the most specific method?
 
Manish Khurana
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies. I am more confused, why only String and not with Integer and any other class..
I didnt knew you could cast null ....Weirder and weirder.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am more confused, why only String and not with Integer and any other class..

I think you misunderstood what Rob was getting at. It works for Integer the same as it works for String, as long as only one of them is present in the code. The problem (of non-decidability on the compiler's part) occurs if you have both a method taking a String parameter, and a method taking an Integer parameter.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!