Slide 1
Slide 2
Slide 3

2D Array with for loop and foreach in java programming (V46)

No Comments

Multidimensional Arrays
2D Array

A 2D array in Java is basically an array of multiple arrays.
It is commonly used to represent matrices or tables.
A 2D array in Java is like a table that has rows and columns.

Syntax:

Example:

Creation with size (rows and columns):

Syntax:

Example:

Combined declaration and creation:

Syntax:


Initialization with values:


Accessing elements:

Source Code:

Copied!
public class Access2DArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3}, //row0
            {4, 5, 6}, //row1
            {7, 8, 9} //row2
        };

        System.out.println(matrix[0][0]);  // First row, first column → Output: 1
        System.out.println(matrix[1][2]);  // Second row, third column → Output: 6
        System.out.println(matrix[2][1]);  // Third row, second column → Output: 8
    }
}

Result:

Source Code:

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

        for (int[] matrix1 : matrix) {
            // Loop through rows
            for (int j = 0; j < matrix1.length; j++) {
                // Loop through columns
                System.out.print(matrix1[j] + " ");
            }
            System.out.println(); // Move to next line after each row
        }
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top