Home » Java programming language

for-each (enhanced for loop) in Java

Java for-each loop/ enhanced for loop: Here, we are going to learn about the enhanced for loop that is known as for-each loop in Java with example.
Submitted by Sanjeev, on April 20, 2019

Java for-each (Enhanced for) loop

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 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 of for-each (enhanced for) loop:

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

It stores each item of the collection in variable and then executes it.

Note: data_type should be the same as the data_type of the collection.

Java code to demonstrate example of for-each (enhanced for) 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.