Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.12. The for-each statement

3.12. The for-each statement
Last updated: 23 January 2013.

The for-each statement is a convenient way to iterate over an array or a collection (you will learn about collections later in the tutorials). Unlike the for statement, the for-each statement does not explicitly use an iterator variable. Here is the syntax of the for-each statement:

for(<type> <element> : <array>){

   
// the statements that are to be executed repeatedly go here

}

Syntax explanation:
In the example shown below, the method forEachLoop declares and initializes an array of characters and prints all of its elements to the standard output:

public class JavaLoops {

   
public void forEachLoop(){

         
char[] myArray = { 'a', 'b', 'c', 'd', 'e' };

         
for(char c : myArray){
               
System.out.println(c);
         
}
    }

}

Create a class named App and call the method forEachLoop:

public class App {

   
public static void main(String[] args) {

         
new JavaLoops().forEachLoop();

   
}

}

The output is:

a
b
c
d
e


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.12. The for-each statement
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.13. The while statement

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7