Menu
Coddy logo textTech

Enhanced For Loop

Part of the Fundamentals section of Coddy's Java journey — lesson 65 of 73.

The enhanced for loop, also known as the for-each loop, provides a simpler way to iterate through arrays and collections. It automatically handles the indexing and retrieval of elements, making the code more readable and less prone to errors.

Here's the basic syntax of an enhanced for loop:

for (data_type element : array_or_collection) {
    // Code to be executed for each element
}
  • data_type: The type of elements in the array or collection.
  • element: A variable that will hold the current element in each iteration.
  • array_or_collection: The array or collection you want to iterate over.

Here's an example:

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}

In this example, the loop iterates over the numbers array. In each iteration, the current element is assigned to the number variable, and the code inside the loop is executed. The output will be:

1
2
3
4
5

The enhanced for loop is especially useful when you need to access each element in a collection without modifying the collection itself. It simplifies the code and makes it more readable.

challenge icon

Challenge

Easy

Create a program that does the following:

  1. Initializes an array of strings named fruits with the values "apple", "banana", "orange", "grape", and "kiwi".
  2. Uses an enhanced for loop to iterate over the fruits array.
  3. In each iteration, prints the current fruit in uppercase using the toUpperCase() method: someString.toUpperCase()

Cheat sheet

The enhanced for loop (for-each loop) provides a simpler way to iterate through arrays and collections without manual indexing:

for (data_type element : array_or_collection) {
    // Code to be executed for each element
}
  • data_type: The type of elements in the array or collection
  • element: Variable that holds the current element in each iteration
  • array_or_collection: The array or collection to iterate over

Example with an integer array:

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}

The enhanced for loop is ideal when you need to access each element without modifying the collection itself.

Try it yourself

public class Main {
    public static void main(String[] args) {
        // Initialize the fruits array
        

        // Use an enhanced for loop to iterate over the array
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals