Static array reference default value vs element access: what happens when printing x[0]? public class Test { private static int[] x; // reference not initialized → null public static void main(String[] args) { System.out.println(x[0]); } }
-
A0
-
Bnull
-
CCompile Error
-
DNullPointerException at runtime
-
EArrayIndexOutOfBoundsException
Answer
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:
xis a static field of typeint[]and is never assigned → defaults tonull.- 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