How to declare/initialize 2D arrays

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

        int[][] myArray = { //change as needed
            {1,2,3,4,5},
            {6,7,8,9,10}
        };

        // 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 2 3 4 5 
6 7 8 9 10 

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]]
String[][] people1 = {
    {"Jonathan","Tarun"},
    {"Srijan","Ian"}
};

String[][] people2 = new String[2][2];
people2[0][0] = "Jonathan";
people2[0][1] = "Tarun";
people2[1][0] = "Srijan";
people2[1][1] = "Ian";

String[][] people3 = new String[2][2];
String[] names = {"Jonathan","Tarun","Srijan","Ian"};
int peopleIndex = 0;

for(int i=0;i<people3.length;i++)
{
    for(int j=0;j<people3.length;j++)
    {
        people3[i][j] = names[peopleIndex];
        peopleIndex++;
    }
}

for(int i = 0; i < people3.length; i++) {
            for (int j = 0; j < people3[i].length; j++) {
                System.out.print(people3[i][j] + " ");
            }
            System.out.println();
        }


Jonathan Tarun 
Srijan Ian