Enhanced For Statement Tutorial

The enhanced for statement (aka for-each loop) is used to iterate through the elements of a collection of objects, such as an array. In this tutorial we are going to build on the knowledge you gained from both the Single Dimensional Array tutorial and the For Loop Statement Tutorial. The nice thing about an enhanced for loop is that you do not need to know the number of elements in the array prior to reading the array. All elements of the array are sequentially read from index 0 through the end of the array. This is how the enhanced for loop is structured:
for (type temp-variable : array) {
    Statements are executed here until all elements of the array have been examined.
}



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md EnhancedFor
C:\Java>cd EnhancedFor
C:\Java\EnhancedFor>Notepad EnhancedFor.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class EnhancedFor {
    public static void main(String args[]) {
        int numberArray[] = new int[11]; // reference variable numberArray assigned to array object of 11 int data type elements
		
        // load the array using a standard FOR statement
        // the array will contain all the even numbers from 0 to 20		
        for (int i = 0; i < numberArray.length; i++) {
            numberArray[i] = i * 2 ;
        }

        // now we will read the array using the ENHANCED FOR statement
        System.out.print("numberArray element values: ");
        for (int tempVar : numberArray) {
            System.out.print(tempVar);
            System.out.print(" ");
        }
        System.out.println();		
    }
}

Now switch back to the command prompt (CMD) and type in javac EnhancedFor.java and press Enter.
Now type in java EnhancedFor and press Enter.


C:\Java\EnhancedFor>javac EnhancedFor.java
C:\Java\EnhancedFor>java EnhancedFor
numberArray element values: 0 2 4 6 8 10 12 14 16 18 20


Final thoughts


Tutorials