Course contentsShow
← Java
Lesson 1294 of 2,87029. Iterators and IterableFree lesson

Enhanced For Loop Syntax and Type Inference

Mastering the for (Type element : iterable) syntax and understanding how Java infers types.

Enhanced For Loop Syntax and Type Inference

You'll learn how to write cleaner iteration code using Java's enhanced for loop and how the compiler automatically infers element types.

The Core Idea

The enhanced for loop (also called the "for-each loop") provides a streamlined syntax for iterating over any Iterable collection. Instead of manually calling iterator(), hasNext(), and next(), you simply declare a variable to hold each element and specify the collection to traverse.

The basic syntax is:

for (Type element : iterable) {
    // use element
}

Here, Type is the element type, element is a variable name you choose, and iterable is any object implementing Iterable<Type>.

Type Inference Makes It Clean

Java's compiler infers the correct type from the collection's generic declaration. If you have a List<String>, the compiler knows each element must be a String:

List<String> names = List.of("Alice", "Bob", "Charlie");

for (String name : names) {
    System.out.println(name.toUpperCase());
}

The compiler translates this into iterator calls behind the scenes, but you don't write that boilerplate yourself. The type String matches the generic parameter of List<String>, ensuring type safety at compile time.

Analogy

Think of it like a conveyor belt at a factory. Instead of manually grabbing items one by one (iterator methods), you stand at one spot and each item automatically comes to you—and you already know what type of item to expect based on what the conveyor belt carries.

When Type Matters

You must declare the correct type or a compatible supertype. If your List<Integer> contains integers, you can iterate with Number or Object, but the declared type affects what methods you can call on element without casting.

Key Takeaway: The enhanced for loop's for (Type element : iterable) syntax relies on compile-time type inference from the collection's generic type, providing concise, type-safe iteration without manual iterator management.