jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Getting unexpected Result. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting unexpected Result." Watch "Getting unexpected Result." New topic
Author

Getting unexpected Result.

Al sha
Greenhorn

Joined: Jan 20, 2004
Posts: 20
Hi ,

Can anyone please explain why am I getting "test2 called" as output instead of throwing null pointer exception for the code mentioned below.

Thanx in advance.

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

public class TestSingle{

public static void main(String st[]){
TestSingle ts = new TestSingle();
ts=null;
ts.test2();
}

public static void test2(){
System.out.println("test2 called");
}

}
---------------------------------------
Output:test2 called.
---------------------------------------
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
Because the test2 method is static, it does not depend on an instance of TestSingle to run.


will work the same way as what you have.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Al sha
Greenhorn

Joined: Jan 20, 2004
Posts: 20
Suppose we are invoking test2() in another class like one below

public class TestSingle1{

public static void main(String args[]){
TestSingle ts2 = new TestSingle();
ts2 = null;
ts2.test2();
}

}


Even this prints out the message in test2(), though the variable ts2 is made to null.
Is it because of the static nature of the method test2() ?
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
It is because of the static nature of the method test2(). If you make the test2() method into an instance method, you will see what you expected.
Al sha
Greenhorn

Joined: Jan 20, 2004
Posts: 20
Hi Marilyn,

Thanks for u r valuable info and timely help.

Regards

Al Sha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting unexpected Result.