Java Enhanced For loop, Examples

Enhanced for loop in java, Java enhanced for loop, Java for-each loop, Enhanced for loop example, Advantageous of for-each loop. Iterating through basic for loop. Iterating through Arrays, Iterating through Collection

Enhanced for loop to overcome the drawbacks of basic for loop and this best suitable for iterating Arrays and Collections.

Syntax:


for ( varaible_declaration : Array or Collection)
{
    //
}

Java Enhanced For loop, Examples



Rules:


1) Variable declaration should be inside for loop. Declaring outside leads to compile time error.
2) After declaration colon(:) is mandatory.
3) Expression should be Array or Collection which is input and iterated over it.

We will see the example program on the following to better understand on basic and for-each.

1) Iterating through basic for loop.
2) Iterating through Arrays
3) Iterating through Collection


1) Iterating through basic for loop:


System.out.println("Iterating basic for loop");
int numbers[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}


Output:

Iterating basic for loop
1
2
3
4
5

Here, Variable declartion and incrementing the variable are requried manual actions. But these are common in basic for loop.
We can minimize these redundent code using advanced enhanced for each loop.


2) Iterating through Arrays:



    System.out.println("Iterating Array using advanced for-each loop.");
int numbersArray[] = { 1, 2, 3, 4, 5 };
for (int i : numbersArray) {
System.out.println(i);
}

Output:

Iterating Array using advanced for-each loop.
1
2
3
4
5


3) Iterating through Collection


        System.out.println("Iterating List using advanced for-each loop.");
List numbersList = new ArrayList<>();
numbersList.add(1);
numbersList.add(2);
numbersList.add(3);
numbersList.add(4);
numbersList.add(5);
for (int listNumber : numbersList) {
System.out.println(listNumber);
}

       
Autoboxing and Unboxing in Java

Output:

Iterating List using advanced for-each loop.
1
2
3
4
5

0 Comments