How to output an array in Java?

In Java, you can output an array using either a loop structure or the toString() method of the Arrays class.

Option 1: Output array elements using a loop structure.

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

Option 2: Print array elements using the toString() method of the Arrays class.

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));

Note: It is necessary to import the java.util.Arrays class in the code, which is done by using import java.util.Arrays;

bannerAds