Java array references and default initialization: determine f2[0] after assigning f2 = f1.\n\npublic class ArrayTest {\n public static void main(String[] args) {\n float f1[], f2[];\n f1 = new float[10];\n f2 = f1;\n System.out.println("f2[0] = " + f2[0]);\n }\n}

Difficulty: Easy

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

More Questions from Declarations and Access Control

Discussion & Comments

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