Print Entire Array in Java: Complete Guide

To print the entire contents of a Java array, you can use the following code:

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        
        // 使用for循环打印数组
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        
        // 使用增强for循环打印数组
        for (int num : array) {
            System.out.println(num);
        }
        
        // 使用Arrays.toString()方法打印数组
        System.out.println(Arrays.toString(array));
    }
}

In the code above, an array of type int called array is first defined, and then each element of the array is printed using a for loop and an enhanced for loop respectively. Additionally, the entire array can be converted to a string using the Arrays.toString() method and printed out.

bannerAds