How to declare/initialize 2D arrays

// Boiler Plate Code public class Main { public static void main(String[] args) {

    */ (Intialize Array Here) */

    // Display Array Code below
    for(int i = 0; i < myArray.length; i++) {
        for (int j = 0; j < myArray[i].length; j++) {
            System.out.print(myArray[i][j] + " ");
        }
        System.out.println();
    }
} }

Main.main(null) 1) All in one

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

2) Empty array and manual input with indexes

// Declare a 3x3 empty 2D array
int[][] matrix = new int[3][3];

// Assign values to the 2D array using indexes
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;

3) Nested For-Loop

int value = 1; // Start value
for (int i = 0; i < matrix.length; i++) {  // Outer loop for rows
    for (int j = 0; j < matrix[i].length; j++) {  // Inner loop for columns
        matrix[i][j] = value++; // Assign value and increment
    }
}

Popcorn Hack 1 (Part 1):

  • Intialize a 2D array of the people in your group grouped based on pairs with 3 different methods
  • ex Array: [[Anusha, Vibha],[Avanthika, Matthew]]