Java Enhanced for Loop

Introduction to java enhanced for loop

In this blog post, we will learn about the java enhanced for loop. We all know about the traditional for loop in a java programming language. The enhanced for loop in java is also known as the for each loop. For each loop of java programming language arrays and collections’ elements are iterated over using the for-each loop (like ArrayList). The improved for loop is another name for it.

Another way for the same is just by limiting the number of variables in the for loop syntax. The exemplar code for the same can be written as:

 

 

for (int i = 0; i < myArray.length; i++) {

System.out.println(myArray[i]);

}

 

 

Another way of writing the same is also shown below:

 

 

for (int myValue : myArray) {

System.out.println(myValue);

 

 

These enhanced for loops can also be created by using the concept of ArrayList in java. The ArrayList is a part of the collection package in java. The syntax for the same is also shown below:

 

 

ArrayList<Integer> list = new ArrayList<Integer>();

list.forEach((n) -> System.out.println(n));

 

 

The best advantage of using the enhanced for loop is that they are really faster and good at iterating the elements of the list. These enhanced for loops are only capable of iterating the elements of the list not for making any changes in the elements of the list. 

 

 

Also Read: pandas explode

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *