Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Arrays in Java

2-Dimensional (2D) Array in Java

A 2D array is a table or matrix where data is stored in rows and columns. It is useful when dealing with structured data like student lists in multiple classes.

Syntax:

dataType[][] arrayName = new dataType[rows][columns];

or

dataType[][] arrayName = {
    {value1, value2},
    {value3, value4}
};

Example:

A list of students in multiple classes.

class MasterBackend {
    public static void main(String[] args) {
        // 2D Array: Students in multiple classes
        String[][] classStudents = {
            {"Ayush", "Rahul"},   // Class 1
            {"Neha", "Priya"}     // Class 2
        };

        System.out.println("Students in multiple classes:");
        for (int i = 0; i < classStudents.length; i++) {
            System.out.print("Class " + (i + 1) + ": ");
            for (int j = 0; j < classStudents[i].length; j++) {
                System.out.print(classStudents[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

Students in multiple classes:
Class 1: Ayush Rahul
Class 2: Neha Priya