The Iterating over Arrays in Java


To iterate over arrays in Java, you can simply use a for loop. Looping should be till the length of the array to display all the elements.

Example

Let us now see an example to iterate over arrays −

public class Demo {
   public static void main(String args[]) {
      int myArray[] = new int[5];
      myArray[0] = 230;
      myArray[1] = 110;
      myArray[2] = 130;
      myArray[3] = 350;
      myArray[4] = 290;
      System.out.println("Array elements...");
      for(int i=0; i < myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}

Output

Array elements...
230
110
130
350
290

Example

We can also iterate over arrays using for loop −

public class Demo {
   public static void main(String args[]) {
      int myArray[] = new int[5];
      myArray[0] = 15;
      myArray[1] = 3;
      myArray[2] = 40;
      myArray[3] = 30;
      myArray[4] = 7;
      System.out.println("Array elements...");
      for(int ele: myArray) {
         System.out.println(ele);
      }
   }
}

Output

Array elements...
15
3
40
30
7
raja
Published on 25-Sep-2019 08:57:06
Advertisements