Enhanced for loop (a.k.a foreach loop):

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse any array (and collection in general) sequentially, till the end, without using the initialization block or the update block.

The syntax of enhanced for loop is:

for(declaration : expression){
  //Statements
}

declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the current array element in the iteration.

expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class EnhancedForLoopDemo {

    public static void main(String args[]) {
        int[] numbers = { 10, 20, 50, 30, 40 };

        for (int x : numbers) {
            System.out.print(x);
            System.out.print(",");
        }
        System.out.print("\n");
        String[] names = { "James", "Larry", "Tom", "Lacy" };
        for (String name : names) {
            System.out.print(name);
            System.out.print(",");
        }
    }
}

Check the result.

Processing arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. Iterating an array is one of the most commonly occurring code blocks in Java. Here is an example of the for and foreach loops used to print, compute sum and finding the largest element:

public class TestArray {

    public static void main(String[] args) {
        double[] myList = { 1.0, 2.5, 4.0, 3.5 };

        // Print all the array elements using for
        for (int i = 0; i < myList.length; i++) {
            System.out.println(myList[i] + " ");
        }

        // Summing all elements using foreach
        double total = 0;
        for (double i : myList) {
            total += i;
        }
        System.out.println("Total is " + total);

        // Finding the largest element using foreach
        double max = myList[0];
        for (double i : myList) {
            if (i > max) {
                max = i;
            }
        }
        System.out.println("Max is " + max);
    }
}

Run the program, examine and verify the result.

Enhanced for-loop can used for not only arrays but also for Collection objects. You will learn some Collection classes in the next lesson.

results matching ""

    No results matching ""