How can the entire two-dimensional array be output in Java?

To output a two-dimensional array as a whole, you can utilize nested loops to iterate through each element and print them one by one.

Here is an example code:

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

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

When you run the above code, it will output each element of the two-dimensional array. The output is as follows:

1 2 3 
4 5 6 
7 8 9 

In the code above, the outer loop controls the number of rows, while the inner loop controls the number of columns. The variable arr.length represents the number of rows in the two-dimensional array, and arr[i].length represents the number of columns in the i-th row. System.out.print() is used to print each element with spaces in between. After the inner loop finishes, System.out.println() is used to print a newline character, ensuring that each row’s elements are displayed on a separate line.

bannerAds