Java arrays: Which one of the following declarations causes a compiler error?

Difficulty: Easy

Correct Answer: int[][] scores = {2,7,6}, {9,3,45};

Explanation:


Introduction / Context:
Two-dimensional array initialization in Java requires proper nesting of braces to form rows. This question focuses on identifying the malformed declaration among otherwise valid array declarations.



Given Data / Assumptions:

  • Single- and multi-dimensional arrays are being declared.
  • Boxed types and primitive arrays are mixed to test syntax understanding.


Concept / Approach:
A two-dimensional array literal uses nested braces: new int[][] { {row1}, {row2} } or simply { {row1}, {row2} } when used with a declaration. Flat lists without nested braces are illegal for 2D arrays.



Step-by-Step Solution:

Option A creates a 1D int array with three elements → valid.Option B attempts to declare a 2D int array but uses two comma-separated flat lists instead of nested row braces → invalid syntax.Option C declares a 1D String array using a literal → valid.Option D creates a new boolean array using an initializer list → valid.Option E declares an Integer array with boxed values → valid.


Verification / Alternative check:
Correct form for B would be int[][] scores = { {2,7,6}, {9,3,45} };



Why Other Options Are Wrong:
They all follow legal Java syntax for array declarations and initializations.



Common Pitfalls:
Forgetting inner braces for multi-dimensional initializers; mixing up new int[] { ... } versus size-based creation.



Final Answer:
int[][] scores = {2,7,6}, {9,3,45};

More Questions from Declarations and Access Control

Discussion & Comments

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