How to loop through an array in java?

Arrays are fundamental data structures, and iterating over them is a common operation.

Example:


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

Solution:

Using enhanced for-loop for simpler array iteration:


  for(int num : numbers) {
      System.out.println(num);
  }
  

Beginner's Guide to Java