aspose file tools *
The moose likes Beginning Java and the fly likes Accessing static variable via null reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing static variable via null reference" Watch "Accessing static variable via null reference" New topic
Author

Accessing static variable via null reference

amit ang
Ranch Hand

Joined: Sep 28, 2001
Posts: 38
public class Test {
public static int intTmp = 10;
public Test() {
}
public static void main(String[] args) {
Test test1 = new Test();
test1=null;
System.out.println("Here it is : "+test1.intTmp);
}
output :
Here it is : 10
how is this possible any good explaination on this ?
cheers,
Amit
[ EJFH -- added sensible subject line ]
[ April 28, 2004: Message edited by: Ernest Friedman-Hill ]
Himanshu Pathak
Greenhorn

Joined: Apr 26, 2004
Posts: 9
just remove the static keyword and try to execute your code.
it will throw a NullPointerException
also when i compiled your code it gives a warning which is quite understood.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

... and a beginner topic too...
... and a bad subject ...
[ April 28, 2004: Message edited by: Stefan Wagner ]

http://home.arcor.de/hirnstrom/bewerbung
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Stefan Wagner:
... and a beginner topic too...
... and a bad subject ...

Indeed. Changed subject, moved to JiG (Beginner).


[Jess in Action][AskingGoodQuestions]
Jeffrey Hunter
Ranch Hand

Joined: Apr 16, 2004
Posts: 305
You do not need an actual instantiation of the class to call the static variable.
Max Rahder
Ranch Hand

Joined: Nov 06, 2000
Posts: 177
Amit, a static field is associated with the class, not with an instance of the class. Therefore, Java uses the data type of the variable to resolve "intTmp". It doesn't matter that the reference is null, because it doesn't need the reference to get the value of intTmp.
amit ang
Ranch Hand

Joined: Sep 28, 2001
Posts: 38
Hi Max,
Ya, i know that static is identified by class. But, when you access it through reference
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
your reference doesn't point to anything...
NEVER access a static method/member through a reference, it's bad practice (even though not actually prohibited).
A static member doesn't relate to any instance, so accessing it as if it did is a big nono.


42
amit ang
Ranch Hand

Joined: Sep 28, 2001
Posts: 38
Thanks guys,
Got it. It's all to do with the associated TYPE rather then instance for the static declarations.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing static variable via null reference