for each loop java vs for loop code example
Example 1: java for each
for(<Data Type> item : itemset) {
}
Example 2: 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 3: java foreach
List<String> someList = new ArrayList<String>();
for (String item : someList) {
System.out.println(item);
}
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
Example 5: for each java
public class JavaArray {
public static void main(String[] s) {
int[] age = new int[5];
age[0] = 21;
age[1] = 23;
age[2] = 45;
age[3] = 31;
age[4] = 33;
for (int a : age) {
System.out.println("age= " + a);
}
}
}