Enhanced for Loop Java

Enhanced for Loop Java

In the traditional for loop, we created an iteration variable to iterate through the loop. This means that we are iterating index-wise in the array. Instead of that, we can also directly access the element itself.

So, we create a variable that is of the same base type as the array.

For example, if the array is of char type, then the variable is also of char type because that’s the value it’s going to hold.

Let’s now understand the syntax to understand how are we going to write this in our programs –

for (type varname : arrayname){
//you can directly get the element here in the varname
}

You can just consider that the variable varname, will store the value from the array one at a time, according to the index. Let’s consider an example here so that we can get more clear about the concept. Have a look at the program –

public class ExampleArray {
public static void main(String[] args) {
int[] examplearray = new int[5];
for (int index = 0; index <examplearray.length ; index++) {
examplearray[index] = index*5; // This is just to store something into the array.
}
for (int element : examplearray) {
System.out.println(element);
}
}
}

So, in the above program, we can see that once we have the array created, we can use the enhanced for loop to iterate through the array, element by element. We can simply say that for every element in the array, the variable holds the element. If you try to run this program, we can see all the elements in the output. Now, the readability of the code is also increased, but there are certain limitations with this type of loop.

Here are some limitations of the enhanced for loop, which need to be kept in consideration while using –

  • Here, we are not using the index of the elements while iterating through the loop.
  • Cannot traverse the array in the reverse order.
  • We may not able to change/play with the contents of the array (this may have some exceptions)

There are some other limitations as well here, which we can explore, and encounter while working with the enhanced for loop, for different types of data in the array.