aspose file tools*
The moose likes Beginning Java and the fly likes null return type-urgent attn.pls. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null return type-urgent attn.pls." Watch "null return type-urgent attn.pls." New topic
Author

null return type-urgent attn.pls.

sekar thangavel
Greenhorn

Joined: Mar 24, 2001
Posts: 3
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

Joined: Jan 09, 2001
Posts: 1492
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

Joined: Sep 29, 2000
Posts: 8521
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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: null return type-urgent attn.pls.