Java array references and default initialization: determine f2[0] after assigning f2 = f1. public class ArrayTest { public static void main(String[] args) { float f1[], f2[]; f1 = new float[10]; f2 = f1; System.out.println("f2[0] = " + f2[0]); } }
-
AIt prints f2[0] = 0.0
-
BIt prints f2[0] = NaN
-
CAn error at f2 = f1; causes compile to fail.
-
DIt prints the garbage value.
-
EAn exception is thrown at runtime.
Answer
Correct Answer: It prints f2[0] = 0.0
Explanation
Introduction / Context: This question is about Java array references, aliasing, and default values of primitive arrays. Java initializes arrays of primitives to their default values: 0 for numeric types, false for boolean, and \u0000 for char. Assigning one array reference to another creates an alias, not a copy.
Given Data / Assumptions:
- f1 is a new float[10], so all elements are initialized to 0.0f.
- f2 = f1 means f2 refers to the same array object as f1.
- No writes occur before reading f2[0].
Concept / Approach: Because f2 and f1 reference the same array, reading f2[0] is equivalent to reading f1[0], which is the default 0.0f for a newly allocated float array.
Step-by-Step Solution:
Allocate f1 → all entries 0.0.Assign f2 = f1 → both references point to the same array.Access f2[0] → value is 0.0.Print → "f2[0] = 0.0".Verification / Alternative check: Writing f1[0] = 2.5f before printing would make f2[0] also 2.5 because of aliasing.
Why Other Options Are Wrong:
- NaN: Default is not NaN; NaN results from specific operations.
- Compile error: Assignment between compatible array references is legal.
- Garbage value: Java does not leave primitives uninitialized in arrays.
- Runtime exception: No out-of-bounds or null dereference occurs.
Common Pitfalls: Expecting C-like uninitialized memory or assuming f2 becomes a deep copy rather than an alias.
Final Answer: It prints f2[0] = 0.0