for each loop vs for loop java code example
Example 1: for vs foreach loop java
1-
For Loop:
-It is flexible to iterate array
both ascending and descending order.
For Each:
-It iterates from initial to end
2-
For Loop:
-It runs until given condition become false
For Each:
-Keeps execution until last element
get executed
3-
For Loop:
-It use index
For Each:
-It use iteration
4-
For Loop:
-Accepts both object collections and non object collections
For Each:
-Accepts only object collections
Example 2: for-each loop in java
for(<DataType of array><variablename> : <Array to be iterated>)
{
}
Example 3: for-each loop in java
import java.util.*;
public class ForEachLoopExample
{
public static void main(String[] args)
{
int[] numbers = {2, 4, 6, 8, 10};
for(int n : numbers)
{
System.out.println(n);
}
}
}
Example 4: for loop vs for each loop
1-
For Loop:
-It is flexible to iterate array
both ascending and descending order.
For Each:
-It iterates from initial to end
2-
For Loop:
-It runs until given condition become false
For Each:
-Keeps execution until last element
get executed
3-
For Loop:
-It use index
For Each:
-It use iteration
4-
For Loop:
-Accepts both object collections and non object collections
For Each:
-Accepts only object collections