How to print an array in Java?

To print an array, you can use the following code:

int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
}

This code utilizes a for loop to iterate through each element in the array and prints them out using the System.out.print() method. Each element is separated by a space.

To print a two-dimensional array, you can use two nested for loops to iterate through each element. For example:

int[][] twoDimArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < twoDimArray.length; i++) {
    for (int j = 0; j < twoDimArray[i].length; j++) {
        System.out.print(twoDimArray[i][j] + " ");
    }
    System.out.println();
}

This code first iterates through each row, then within each row iterates through each element and prints it using the System.out.print() method. The elements are separated by spaces and a new line is printed at the end of each row.

bannerAds