In Java, which three are legal array declarations among the following?

Difficulty: Easy

Correct Answer: 1, 2, 4

Explanation:


Introduction / Context:
Java supports several syntactic styles for array declarations, including placing brackets after the type or after the variable name. Some C-like forms are illegal in Java.



Given Data / Assumptions:

  • Candidates: (1) int [] myScores []; (2) char [] myChars; (3) int [6] myScores; (4) Dog myDogs []; (5) Dog myDogs [7];
  • Dog is assumed to be a class type.


Concept / Approach:
Legal forms: type[] var; or type var[];. Multi-dimensional (jagged) arrays can be declared like int[] a[];. Illegal forms include specifying the size in the declaration without an initializer on the left-hand side (C-style).



Step-by-Step Solution:

(1) int [] myScores []; → legal (2D, jagged declaration).(2) char [] myChars; → legal (1D char array declaration).(3) int [6] myScores; → illegal in Java; size cannot appear here.(4) Dog myDogs []; → legal (array of Dog references).(5) Dog myDogs [7]; → illegal (size specified at declaration without initializer in this position).


Verification / Alternative check:
Try compiling each; (3) and (5) fail with syntax errors.



Why Other Options Are Wrong:
Any set including (3) or (5) is invalid.



Common Pitfalls:
Transferring C/C++ array syntax to Java; mixing declaration and allocation incorrectly.



Final Answer:
1, 2, 4

More Questions from Language Fundamentals

Discussion & Comments

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