Which syntax is incorrect to initialize a two-dimensional array in Java?
2024
Which syntax is incorrect to initialize a two-dimensional array in Java?
Answer: D. int myarr = new int[3][4]; — Concept In Java, a variable declaration fixes the variable’s type, while an initializer expression has its own type. An assignment is valid only when the…
- A.
int myarr[][] = new int[3][4];
- B.
int[][] myarr = {{1, 2, 3}, {4, 5, 6}};
- C.
int[][] myarr = new int[3][4];
- D.
int myarr = new int[3][4];
- E.
Question not attempted
Attempted by 298 students.
Show answer & explanation
Correct answer: D
Concept
In Java, a variable declaration fixes the variable’s type, while an initializer expression has its own type. An assignment is valid only when the initializer type is assignment-compatible with the declared variable type; a two-dimensional int array has type int[][].
Application
Read the declaration int myarr: it declares myarr as one scalar int.
Evaluate new int[3][4]: it creates an array of three int[] rows, each with four elements, so its type is int[][].
Compare the types: Java cannot assign an int[][] reference to an int variable, so int myarr = new int[3][4]; is a compile-time type error.
Contrast
int myarr[][] = new int[3][4]; places the brackets after the variable name; myarr still has type int[][].
int[][] myarr = {{1, 2, 3}, {4, 5, 6}}; declares int[][] and supplies a nested array initializer.
int[][] myarr = new int[3][4]; declares int[][] and creates a matching int[][] value.
Question not attempted records no submitted syntax and is not itself a Java initialization statement.
Cross-check
A Java compiler diagnoses the scalar declaration with an incompatible-types error because int[][] cannot be converted to int. Therefore, the incorrect syntax is int myarr = new int[3][4];.