Java 2D Array Example: Initialization, Row Sum Calculation

This Java code example illustrates the use of a 2D array to perform basic operations. It initializes a grid, calculates the sum of each row, and finds the maximum element within the array. This example helps in understanding how to manipulate and traverse multidimensional arrays effectively.

Code Example

public class MultiDimensionalArrayExample {
    public static void main(String[] args) {
        // Initializing a 2D array representing a grid
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Calculating the sum of each row
        for (int i = 0; i < grid.length; i++) {
            int rowSum = 0;
            for (int j = 0; j < grid[i].length; j++) {
                rowSum += grid[i][j];
            }
            System.out.println("Sum of row " + i + ": " + rowSum);
        }

        // Finding the maximum element in the 2D array
        int max = grid[0][0];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] > max) {
                    max = grid[i][j];
                }
            }
        }
        System.out.println("Maximum element in the grid: " + max);
    }
}

Explanation

  1. Initializing a 2D Array: Represents a simple 3×3 grid.
  2. Calculating Row Sums: Iterates through each row, calculating the sum of its elements.
  3. Finding Maximum Element: Iterates through the array to find the maximum value.

This example highlights basic operations on a 2D array, including summing rows and identifying the maximum element.