Let’s learn difference between for and for each loop in java.
Difference between for and for each loop in java
Here’s the difference between for and for each loop.
for loop | for each loop |
There is no sequence in execution. Here in for loop we can change counter as per our wish. | Executes in sequence. Counter is increased by one. |
was introduced from start, JDK 1. | was introduced from JDK 5 onwards. |
no need of implementing interface. | To loop over containers using for each loop, container should implement Iterable interface. |
can have access to index. Hence can replace element in an array. | can’t replace element at given index since there is no access to array index. |
counter can increment and decrement. | we can only iterate in incremental order cannot decrement. |
Here’s the program on difference between for and for each loop.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DifferenceBetween { public static void main(String[] args) { List<String> players = new ArrayList<>(Arrays.asList("Virat", "Rohit", "Dhoni")); // iterate over List using for loop System.out.println("using for loop: "); for(int a = 0; a < players.size(); a++) { System.out.println(players.get(a)); } // iterate over List using enhanced for loop System.out.println("using for each loop: "); for(String str : players) { System.out.println(str); } } }
Output:
using for loop:
Virat
Rohit
Dhoni
using for each loop:
Virat
Rohit
Dhoni
Also read – static keyword in java