Static array reference default value vs element access: what happens when printing x[0]?\n\npublic class Test {\n private static int[] x; // reference not initialized → null\n public static void main(String[] args) {\n System.out.println(x[0]);\n }\n}

Difficulty: Easy

Correct Answer: NullPointerException at runtime

Explanation:


Introduction / Context:
This checks the difference between an array reference's default value and the default values of array elements. A static array reference that is not explicitly initialized remains null. Accessing an element through a null reference causes a runtime exception.


Given Data / Assumptions:

  • x is a static field of type int[] and is never assigned → defaults to null.
  • Main tries to print x[0].


Concept / Approach:
In Java, object references default to null. Although an allocated int[] would have elements defaulting to 0, here the array object does not exist. Any attempt to index a null array reference throws NullPointerException.


Step-by-Step Solution:
Field initialization: x == null. Expression x[0] requires dereferencing x first. Dereferencing null triggers NullPointerException at runtime.


Verification / Alternative check:
Initialize x = new int[1]; then x[0] prints 0 because the element defaults to 0. The distinction is between the reference and the array instance.


Why Other Options Are Wrong:
“0” would require an allocated array; “null” is not printed because the code never reaches printing a value; compilation is valid.


Common Pitfalls:
Assuming default element values apply even when the array reference is null; forgetting that arrays are objects.


Final Answer:
NullPointerException at runtime

More Questions from Objects and Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion