Arrays and the Enhanced For Loop
What you'll learn: You'll discover that Java arrays work seamlessly with the enhanced for loop, even though they aren't technically collections and don't implement the Iterable interface.
The Surprising Truth About Arrays
Here's something interesting: when you use an enhanced for loop (also called "for-each") with an array, it works perfectly—yet arrays don't actually implement the Iterable interface. Java's compiler treats arrays as a special case, giving them enhanced for loop support at the language level.
Think of it like a VIP pass: most guests (collections) need to show their Iterable membership card to use the enhanced for loop, but arrays get automatic entry because the language itself vouches for them.
How It Works
When you write an enhanced for loop with an array, the compiler translates it into a traditional indexed loop behind the scenes:
int[] numbers = {10, 20, 30, 40};
// Enhanced for loop with array
for (int num : numbers) {
System.out.println(num);
}
The compiler converts this to something equivalent to:
for (int i = 0; i < numbers.length; i++) {
int num = numbers[i];
System.out.println(num);
}
Why This Matters
This special treatment means you can use the same clean, readable syntax for both arrays and collections, even though they work differently underneath. Arrays get this privilege because they're a fundamental part of the Java language, predating the Collections Framework.
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println("Hello, " + name);
}
Key Takeaway: Arrays work with the enhanced for loop through special compiler support, not by implementing Iterable—making them a unique exception to the normal iteration contract.