</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to demonstrate 2D (two-dimensional) array declaration and traversal.

Answer

Two-Dimensional Array in Java

Java
public class TwoDimArray {
    public static void main(String[] args) {

        // Declare a 2D array: 3 rows, 2 columns
        int a[][] = new int[3][2];

        // Assign values to each cell
        a[0][0] = 100;
        a[0][1] = 200;

        a[1][0] = 300;
        a[1][1] = 400;

        a[2][0] = 500;
        a[2][1] = 600;

        // Alternative: inline initialization
        // int a[][] = { {100,200}, {300,400}, {500,600} };

        System.out.println("Rows:    " + a.length);       // 3
        System.out.println("Columns: " + a[0].length);    // 2

        // Traverse using nested enhanced for loops
        System.out.println("All elements:");
        for (int[] r : a) {           // r = each row (1D array)
            for (int c : r) {         // c = each element in the row
                System.out.println(c);
            }
        }
    }
}

Output

CODE
Rows:    3
Columns: 2
All elements:
100
200
300
400
500
600

Inline Initialization

Java
// Declare and initialize in one line
int[][] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

System.out.println("Rows: " + matrix.length);       // 3
System.out.println("Cols: " + matrix[0].length);    // 3
System.out.println("Center: " + matrix[1][1]);      // 5

Print as Grid (Tabular)

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

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.printf("%-5d", matrix[i][j]);
    }
    System.out.println();
}

Output

CODE
1    2    3
4    5    6
7    8    9

Sum of 2D Array Elements

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

for (int[] row : matrix)
    for (int val : row)
        sum += val;

System.out.println("Sum: " + sum);  // 45

Automation Testing Relevance

Java
// Read a web table into a 2D array
List<WebElement> rows = driver.findElements(By.css("table tr"));
String[][] tableData  = new String[rows.size()][];

for (int i = 0; i < rows.size(); i++) {
    List<WebElement> cols = rows.get(i).findElements(By.tagName("td"));
    tableData[i] = new String[cols.size()];
    for (int j = 0; j < cols.size(); j++) {
        tableData[i][j] = cols.get(j).getText();
    }
}

// Verify specific cell
assertEquals(tableData[1][2], "Active", "Row 2, Col 3 should be Active");

Follow AutomateQA