- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java For-each Loop (Enhanced For Loop)
In Java, the for-each loop, also known as the enhanced for loop, was introduced in Java 5 as a way to simplify iteration over arrays and collections. Before its introduction, developers had to manage loop counters or iterators manually, which often led to "off-by-one" errors and cluttered code. The enhanced for loop removes this boilerplate, making your code cleaner and more expressive.
Syntax:
for (dataType element : arrayOrCollection) {
// Code to execute for each element
}
dataType:
- Specifies the data type of the elements stored within the array or collection. This must match the type of the objects you are iterating over.
element:
- This is a local variable that acts as a placeholder. In every step of the loop, Java automatically assigns the next value from the source to this variable.
arrayOrCollection:
- This is the data source you want to step through. It must be either an array or an object that implements the
Iterableinterface (like List, Set, or Queue).
for (String name : names) can be read as "For each String name in the names collection."
For-each Loop Example with Arrays:
When working with arrays, the for-each loop is the most readable way to access every item. It handles the array boundaries automatically, so you don't have to worry about array.length.
int[] numbers = {10, 20, 30, 40, 50};
// Calculate the sum of all elements
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Total Sum: " + sum);
for loop with a counter.
Enhanced For Loop with Collections:
The enhanced for loop shines when used with Java Collections like ArrayList or HashSet. It provides a consistent way to traverse data regardless of how that data is stored internally.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println("Processing user: " + name.toUpperCase());
}
ConcurrentModificationException. If you need to remove items while looping, use an Iterator or the removeIf() method.
Practical Real-World Example: Processing Objects
In professional development, you'll rarely just loop over integers. More often, you'll iterate over a list of custom objects, such as processing orders in an e-commerce system:
class Product {
String name;
double price;
Product(String n, double p) { this.name = n; this.price = p; }
}
List<Product> cart = Arrays.asList(new Product("Laptop", 1200.0), new Product("Mouse", 25.0));
for (Product item : cart) {
if (item.price > 100) {
System.out.println("Expensive item: " + item.name);
}
}
Summary
The for-each loop provides a concise and readable way to iterate over arrays or collections in Java, reducing the need for explicit indexing and making code more expressive. By abstracting away the iteration logic, it helps prevent common bugs and improves the maintainability of your codebase. Understanding how to use the enhanced for loop is essential for efficient iteration in modern Java programs.