In Java, which two of the following float-array declarations cause a compiler error? Choose all that apply. float[] f = new float(3); float f2[] = new float[]; float[] f1 = new float[3]; float f3[] = new float[3]; float f5[] = {1.0f, 2.0f, 2.0f};

Difficulty: Easy

Correct Answer: 1, 2

Explanation:


Introduction / Context:
This problem checks your knowledge of valid Java array declarations and initializations for the primitive type float. The key ideas are using square brackets for lengths, and the rules for when size specifiers or initializer lists are required.



Given Data / Assumptions:

  • We are declaring one-dimensional arrays of type float.
  • We must identify which lines fail to compile based on Java syntax for arrays.
  • All code snippets are assumed to be inside a valid method or class context.


Concept / Approach:
In Java, array creation requires square brackets for the dimension size, for example new float[3]. When using an anonymous array initializer, you either provide the size with brackets or a brace-enclosed list, not both partially. Specifically: new float[] with no initializer is illegal; you must provide {...} or an explicit size like new float[n].



Step-by-Step Solution:

Check 1: float[] f = new float(3); → invalid; must be new float[3] (parentheses are not allowed).Check 2: float f2[] = new float[]; → invalid; an empty bracket form requires an initializer list, e.g., new float[] {1f,2f}.Check 3: float[] f1 = new float[3]; → valid sized array.Check 4: float f3[] = new float[3]; → valid alternative bracket placement.Check 5: float f5[] = {1.0f, 2.0f, 2.0f}; → valid initializer list.


Verification / Alternative check:
Compiling a minimal class with each line confirms errors for 1 and 2 and successful compilation for 3, 4, and 5.



Why Other Options Are Wrong:
Options involving 3, 4, or 5 mark valid declarations as errors; those are legal.



Common Pitfalls:
Using parentheses instead of square brackets for array size; forgetting that new float[] must be accompanied by an initializer list.



Final Answer:
1, 2

More Questions from Declarations and Access Control

Discussion & Comments

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