Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null return type-urgent attn.pls.

 
sekar thangavel
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..see the code below.
class sekar{
static sekar method1(){
return null;
}
static void method2(){
System.out.println("Hello");
}
public static void main(String ar[]){
method1().method2();
}
}
I expect the execution of the code to result in NullPointerException as the method1() returns null. But actually the method2 gets executed and prints "hello". Explanation urgently needed.

------------------
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sekar,
You won't get a null pointer exception because you are dealing with static methods. To call a static method the JVM only needs to know the class of the object. Since your method1 returns a class type of sekar we can go ahead and run method2 without requiring an object!
Remember, you can only get a NullPointerException when you try and use the object that a reference is pointing to and it is not pointing at anything.
Regards,
Manfred.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
null is a valid thing for a sekar to "be".
From the JLS Introduction:
A variable of a class type can hold a null reference or a reference to an object whose type is that class type or any subclass of that class type.

It would be easier to see if you wrote it:

It is not incorrect to set nullSekar to null, and does not prevent the next statement from executing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic