2

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

1 Comment

That clears my thoughts, about reference null and period operator in this case.Thanks alot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.