Iterating over Arrays in Java

Java 8Object Oriented ProgrammingProgramming

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

To iterate over arrays in Java, you can use the foreach loop −

Example

public class Demo {
   public static void main(String[] args) {
      double[] myList = {20.3, 35.7, 50.8, 70.2, 90.8};
      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

Output

20.3
35.7
50.8
70.2

You can also iterate over arrays in Java using the for loop −

Example

public class Demo {
   public static void main(String[] args) {
      double[] myList = {50.5, 100.2, 200.5, 400.6, 500.5, 700.8, 900.2, 1000.5};
      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
   }
}

Output

50.5
100.2
200.5
400.6
500.5
700.8
900.2
1000.5
raja
Published on 24-Sep-2019 07:24:59
Advertisements