Reputation: 151
Why is a null reference exception not thrown when I try to print the value of a static field value from an uninitialized instance of a class.
I expected a Null reference exception in the following code:
public class Check {
static int i=1;
public static void main(String []args)
{
Check ch = null;
System.out.print(ch.i);
}
}
Produces output as: 1
.
Upvotes: 2
Views: 76
Reputation: 171
In your snippet, i
is static that means it may not need to be instantiated that means the default constructor need not be called as:
Check ch= new Check();
as i
is static
only a reference will suffice. Like you did,
Check ch = null;
So doing,
System.out.println(ch.i);
will print the value of i
that is 1 from static context
Upvotes: 2
Reputation: 14958
Given that i
is static
(it can be accessed through the class directly, no need to use an instance for it), in the code ch.i
, the compiler checks for the type of the reference of ch
(Check
) and use it for accessing the variable i
instead of using the class instance. This mean null
(the instance) is not used at all (thus we don't get any exception).
That's it, the output of Check.i
is 1
.
Upvotes: 1
Reputation: 589
Because i is a static variable, it does not matter whether its value is obtained from an object or from the class.
See the note here:
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Upvotes: 1