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:
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:
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
Discussion & Comments