0
0
Javaprogramming~5 mins

Enhanced for loop in Java

Choose your learning style9 modes available
Introduction

The enhanced for loop helps you go through all items in a list or array easily without using a counter.

When you want to print all items in a list of names.
When you need to add up all numbers in an array.
When you want to check each element in a collection one by one.
When you want to avoid mistakes with counting indexes in loops.
Syntax
Java
for (type item : collection) {
    // use item here
}

The type is the data type of each item in the collection.

The collection can be an array or any object that implements Iterable.

Examples
This prints each number in the array numbers.
Java
int[] numbers = {1, 2, 3};
for (int num : numbers) {
    System.out.println(num);
}
This prints each fruit name from the fruits array.
Java
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
    System.out.println(fruit);
}
This loops through a list of colors and prints each one.
Java
List<String> colors = List.of("red", "green", "blue");
for (String color : colors) {
    System.out.println(color);
}
Sample Program

This program uses an enhanced for loop to print a sentence for each pet in the array.

Java
public class Main {
    public static void main(String[] args) {
        String[] pets = {"dog", "cat", "parrot"};
        for (String pet : pets) {
            System.out.println("I have a " + pet);
        }
    }
}
OutputSuccess
Important Notes

You cannot change the collection inside the enhanced for loop.

It is simpler and less error-prone than a regular for loop with an index.

Summary

The enhanced for loop is a simple way to go through all items in arrays or collections.

It avoids manual counting and makes code easier to read.