Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Null Problem

 
Ramesh Sahu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code:
--------------------------------------------------------------------------------


class AQ{
public void math(Object o){
System.out.println("ob ver");
}
public void math(String o){
System.out.println("str ver");
}
public static void main(String str[]){
AQ q=new AQ();
q.math(null);
}
}


--------------------------------------------------------------------------------

when I run the above code the output is
str ver

why?
[ July 31, 2008: Message edited by: Ramesh Sahu ]
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-----------------------------------------------------------------
Java choose nearly(closest) matching method for the reference
-----------------------------------------------------------------
 
Ramesh Sahu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can a null be matched to anything else?
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when I run the above code the output is
str ver


Hi
I guess you are aware with the widening concept. In which if there are methods
void m (int i)
void m (Integer i)
void m (Object o)
void m(Object... args)

if an int i =5 is passed

so the preference wiil be given in the order
primitive type
wrapper class
object
varArgs

So considering in your case, method with String parameter will be called
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can a null be matched to anything else?


you can define

String str = null;

I guess this will answer the question.
 
Sandeep Bhandari
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to add, its working the same way with 1.4 and 1.3 too.



makes the call to math method ambiguous

and the following code



results in the output of

"ob ver"

Hope that makes some sense
[ July 31, 2008: Message edited by: Sandeep Bhandari ]
 
Sandeep Bhandari
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also guess the output of following program


 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sandeep Bhandari:
System.out.println("ob ver");


Hai, you are giving same message in both a case...anyway here object reference will take precedence
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic