Java Array Iteration Methods Explained

In Java, there are several ways to iterate through an array, with some common methods including:

  1. Loop through the array using a for loop.
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}
  1. Use enhanced for-loop to iterate through the array (also known as for-each loop).
int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
    System.out.println(num);
}
  1. Print the elements of an array using the toString() method of the Arrays class.
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
  1. Iterate through a List after converting an array using the asList() method of the Arrays class.
int[] arr = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(arr);
for (int num : list) {
    System.out.println(num);
}

These are common methods for traversing arrays, choose the method that fits your specific situation.

bannerAds