JAVA For Each Loop
For each loop or Enhance For loop is a extended version of basic for loop which was introduced in Java 5. For each loop is designed to make iteration over arrays and collections much easier. For each loop also makes the code more readable. In this post we will learn about basics of For each loop using Arrays. We will discuses more about For Each loop when we learn about Collections and Iterator.
Syntax of For Each Loop:-
Example of For Each Loop:- This is a very simple example in which we will traverse an array using For Each loop and print all the elements of the array.
To understand the difference between Basic For loop and For Each Loop, here is the same program using For Loop.
Advantages of For Each Loop:-
Syntax of For Each Loop:-
for (type var : arr) { //body-of-loop |
Example of For Each Loop:- This is a very simple example in which we will traverse an array using For Each loop and print all the elements of the array.
public class ForLoop { |
To understand the difference between Basic For loop and For Each Loop, here is the same program using For Loop.
public class ForLoop { |
Advantages of For Each Loop:-
- Less number of variables are used
- Less chance of errors
- Improve Readability
Limitation of For Each Loop:-
- Cannot traverse multiple collection at once.
- Iterates only forward by single steps.