For Each Loop in Java

By Sanjeev Last updated : January 29, 2024

The for loop is used to execute a block of statements, multiple times if the user knows exactly how many iterations are needed or required.

Java For Each (Enhanced For) Loop

Java supports an enhanced version of for loop which is also called for-each loop or enhanced for loop. This loop works on collections (iterable). It iterates over each element of the sequence on by one and executes them.

Note

Unlike for loop, you cannot alter the content of the sequence inside the for-each loop.

Syntax

Here is the syntax of enhance for (for each) loop in Java:

for (data_type variable : collection){
    //body of the loop;
}

It stores each item of the collection in variable and then executes it. The data_type should be the same as the data_type of the collection.

Example

Here is an example of Java for each (enhance) loop.

// java program to demonstrate example of
// for-each (enhanced for) loop
//file name: includehelp.java

public class includehelp {
    public static void main(String[] args) {
        int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        System.out.println("Demonstration of for-each loop");
        // for-each loop iterating over array
        // with the variable x
        // if you change the value of x inside
        // the body of the loop then original
        // value of the array will remain unaffected
        for (int i : array)
            System.out.println(i);
    }
}

Output

Demonstration of for-each loop
1
2
3
4
5
6
7
8
9
 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.