How to iterating over 2D array in Java

3 Answers

0 votes
public class Main {
    public static void main(String[] args) {
        int[][] array = {    
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        for (int i = 0; i < array.length; i++) { // Outer loop for rows
            for (int j = 0; j < array[i].length; j++) { // Inner loop for columns
                System.out.print(array[i][j] + " ");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}




/*
run:

1 2 3 
4 5 6 
7 8 9 

*/

 



answered Jul 22, 2025 by avibootz
0 votes
public class Main {
    public static void main(String[] args) {
        int[][] array = {    
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        for (int[] row : array) { // Outer loop for rows
            for (int element : row) { // Inner loop for elements in the row
                System.out.print(element + " ");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}




/*
run:

1 2 3 
4 5 6 
7 8 9 

*/

 



answered Jul 22, 2025 by avibootz
0 votes
import java.util.Arrays;

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

        Arrays.stream(array).forEach(row -> {
            Arrays.stream(row).forEach(element -> System.out.print(element + " "));
            System.out.println(); // Move to the next line after each row
        });
    }
}




/*
run:

1 2 3 
4 5 6 
7 8 9 

*/

 



answered Jul 22, 2025 by avibootz
...