Reputation: 2192
When I run this code it print twice 0 but i don't undrestand why after affect the object k to null the value of count still printed 0 but when i delete static before count and execute this program it print first 0 and then i print an exception Exception in thread "main" java.lang.NullPointerException. Please Can you resolve this problem.
public class Test{
public static int count=0;
public static void main(String[] args){
Test t = new Test();
System.out.println(t.count); // 0
t=null;
System.out.println(t.count); // 0
}
}
Upvotes: 1
Views: 1657
Reputation: 8758
static
variables in Java are defined at class level and you do not need an object of that class to reference static variable.
And even if you write t.count
JVM will instead do conventional Test.count
instead (it will replace name of variable with name of its class).
And below extract from JLS: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.11.1
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception:
class Test3 { static String mountain = "Chocorua"; static Test3 favorite(){ System.out.print("Mount "); return null; } public static void main(String[] args) { System.out.println(favorite().mountain); } } It compiles, executes, and prints:
Mount Chocorua Even though the result of favorite() is null, a NullPointerException is not thrown. That "Mount " is printed demonstrates that the Primary expression is indeed fully evaluated at run time, despite the fact that only its type, not its value, is used to determine which field to access (because the field mountain is static).
Upvotes: 2
Reputation: 236
I assume, you meant t=null;
instead of k=null;
.
The static variables are there always only once in whole program, they aren't bent to the objects. All instances of Test have the same count, always. If you set it to anything else, it will change for all instances. Therefore, you can read the value from null as well. Alternativelly, you can use System.out.println(Test::count)
, which will also print 0, without the need of any object of class Test.
Upvotes: 1