Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting unexpected Result.

 
Al sha
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Al sha
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marilyn,

Thanks for u r valuable info and timely help.

Regards

Al Sha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic