Bird
0
0

How can you create a 2D array in Java where each row has a different number of columns? Choose the correct code snippet.

hard📝 Application Q9 of 15
Java - Arrays
How can you create a 2D array in Java where each row has a different number of columns? Choose the correct code snippet.
Aint[][] arr = new int[3][2]; arr[0].length = 2; arr[1].length = 4; arr[2].length = 3;
Bint[][] arr = new int[3][3]; arr[0].length = 2; arr[1].length = 4; arr[2].length = 3;
Cint[][] arr = new int[3][]; arr[0] = new int[2]; arr[1] = new int[4]; arr[2] = new int[3];
Dint[][] arr = new int[3][3]; arr[0][0] = 1; arr[1][0] = 2; arr[2][0] = 3;
Step-by-Step Solution
Solution:
  1. Step 1: Declare 2D array with undefined column size

    int[][] arr = new int[3][]; creates 3 rows with no fixed columns yet.
  2. Step 2: Assign different column sizes to each row

    Assign arr[0], arr[1], arr[2] with arrays of different lengths.
  3. Final Answer:

    int[][] arr = new int[3][]; arr[0] = new int[2]; arr[1] = new int[4]; arr[2] = new int[3]; -> Option C
  4. Quick Check:

    Declare rows first, then assign columns [OK]
Quick Trick: Declare rows only, then assign each row separately [OK]
Common Mistakes:
  • Fixing columns at declaration
  • Assigning arrays to fixed-size rows
  • Confusing syntax for jagged arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes