Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question : object pointing to null ?

 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please refer to the code below..
runtime exception :Nullpointerexception
but actually i really don't quite get as to what havoc is the line obj1=null;
creating ?
this line really brings in lots of .......
take out this line and all is fine. i really quite don't get it as to why this should matter.
obj1.variable or obj1.method .... what does it matter if the object itself points to a null ? let it point where it points to ? why is it effecting our variable and member references. after all for non-static variables and methods we call them via object references ? right ? If this object is a null then all the calculations go haywire ! why ? what's the big deal here.
We are not even discussing the non-static and static methods here yet. that is second. because for static references then it is ok and apparantly this object reference (obj1) does not matter.

------------------------------
class b {
int k=5;
static void main(String[] s)
{
b obj1 = new b();
obj1 = null;
int t=obj1.k;
System.out.println(t);
}}
----------------------------------------
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is rather a surprising question; why should it matter what thing an object reference points to? It's the only thing that matters.
When an object reference points to null, it points to no particular instance in memory. In that space where no values exist, trying to invoke a value like ob1.k simply has no meaning. The compiler can't acutally catch this because from a compile-time point of view, the type of reference is correct. At run-time, however, there's no 'k' value that's actually there.

------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic