Default values in a newly allocated float array: what exactly prints for f[0]?\n\npublic class Test {\n private static float[] f = new float[2];\n public static void main (String[] args) {\n System.out.println("f[0] = " + f[0]);\n }\n}

Difficulty: Easy

Correct Answer: f[0] = 0.0

Explanation:


Introduction / Context:
This item tests default initialization for primitive array elements in Java. When you allocate an array of a primitive type, each element is set to that type’s default value.


Given Data / Assumptions:

  • f is allocated as new float[2].
  • No further writes occur before printing f[0].


Concept / Approach:
For float, the default element value is 0.0f. When converted to String in concatenation, it prints as 0.0. This differs from reference types, which default to null, and from unallocated arrays (which would throw on indexing).


Step-by-Step Solution:
Allocate f → elements initialized to 0.0f. Access f[0] → value 0.0f. String concatenation prints “f[0] = 0.0”.


Verification / Alternative check:
Write f[0] = 1.5f; and re-run; output becomes f[0] = 1.5. For double[], the default is 0.0 as well, shown with double precision.


Why Other Options Are Wrong:
“0” is an int-looking presentation; Java prints a float/double as “0.0”. The code compiles and runs fine; there is no exception.


Common Pitfalls:
Confusing default array element values with default reference values; mixing up formatting vs. numeric value.


Final Answer:
f[0] = 0.0

More Questions from Objects and Collections

Discussion & Comments

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