Iterating over array in Java

Java Programming Java 8Object Oriented Programming

Array can be iterated easily using two approaches.

  • Using for loop - Use a for loop and access the array using index.

  • Using for-each loop - Use a foreach loop and access the array using object.

Following is an example of using above ways.

Example

 Live Demo

public class Tester {
   public static void main(String[] args) {
      int[] array = {1,2,3,4,5};

      System.out.println("Array: ");
      //Way 1:
      for(int i =0; i< array.length; i++){
         System.out.println(array[i]);
      }
      System.out.println("Array: ");
      //Way 2:
      for (int i : array) {
         System.out.println(i);
      }
   }
}

Output

Array:
1
2
3
4
5
Array:
1
2
3
4
5
raja
Published on 19-Sep-2018 09:04:53
Advertisements