Java For-Each Loop

When we need to iterate through elements / objects stored in an array or collections (e.g ArrayList) we can use java for-each loop.

Java for-each Loop Syntax

Following is the syntax of for-each loop in java:

for( dataType object : arrayName){
// statements to be executed
}

Explanation

arrayName – an array or a collection
object – each item of array/collection is assigned to this variable
dataType – the data type of the array/collection

Example


String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (String vehicle : vehicles) {
System.out.println(vehicle);
}

Limitations of Java for-each loop

  1. Elements / Objects stored in array cannot be modified.
  2. For-each loop do not keep track of index. So we can not obtain array index using For-Each loop
  3. For-each only iterates forward over the array / collection in single steps