Using 2D Array in Java

In Java, the concept of a 2D array can be visualized as a table, wherein each slot or compartment of the table holds another array. Think of it like a grid with rows and columns. To pinpoint an individual element within this grid, two distinct indices are essential: one indicating the row and the other pointing to the column. This dual-index system is what gives it its two-dimensional nature. A fascinating aspect of Java's 2D arrays is their flexibility in row lengths. Unlike other languages, where the number of columns must be uniform across all rows, Java grants the freedom to have varied lengths for different rows. However, in several applications, especially when dealing with matrix computations, having a consistent number of columns in each row becomes crucial. This uniformity simplifies calculations and prevents potential errors from mismatched row lengths. In this Java 2D Array Example, we create a 2D array and manipulate it. Click Execute to run the Java 2D Array Example online and see the result.
Using 2D Array in Java Execute
public class TwoDArrayExample {

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}

        matrix[0][0] = 10;
        System.out.println("Matrix contents:");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
Updated: Viewed: 34 times