Normally we would expect a NullPointerException everytime we access a method or a member variable through a 'null' reference. But, interestingly, there is one case in which you can ! (?)
Take a look at the following Java source code for NullTest.java
public class NullTest {
public static int count = 0;
public static void main(String[] args) {
System.out.println("Will this be a NullPointerException? ");
NullTest app = null;
app.count++;
System.out.println("Or will it print the count: " + app.count);
}
}
Output of the above program
Explanation
The static variables are associated with the class and not with any specific instance of that class. So one can access static member variables or methods even through a 'null' reference !! Ideally use the class name and not the instance name to refer to them as follows.
//
NullTest.count++
//
Piotr - Thank you for illustrating this concept using byte code.
Yagiz - Thank you for your comments.
regards,
Sai Matam.
Posted by: Sai Matam | 05/05/2012 at 08:02 PM
As you mention at the end of the article, static attributes should be accessed using the class name. Using the instance name is allowed but in my opinion it shouldn't be. However I must admit that your post describes an interesting way showing the difference between the instance scope and the class scope.
Posted by: Yagiz | 05/05/2012 at 12:31 PM
Great example!
In the bytecode (javap -c NullTest) you can see:
...
12: getstatic #5; //Field count:I
15: iconst_1
16: iadd
17: putstatic #5; //Field count:I
20: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
...
So the compiled code is referring to the static field, omitting the instance of NullTest.
Regards.
Posted by: Piotr Nowicki | 05/05/2012 at 07:32 AM