Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
The foreach statement, also known as the enhanced for loop, was introduced in Java 1.5 to simplify the process of iterating over arrays and collections (e.g., ArrayList, HashSet, etc.). The foreach loop eliminates the need for an index variable, making the code more readable and less prone to errors.
Syntax:
for (type variable : array/collection) { // Code block to be executed }
The foreach loop can be used to iterate over an array, accessing each element in turn.
Example:
public class ForeachArrayExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println("Number: " + number); } } }
In this example, the foreach loop iterates over the numbers
array, assigning each element to the variable number
in each iteration.
The foreach loop can also be used to iterate over collections, such as ArrayList, HashSet, etc.
Example:
import java.util.ArrayList; import java.util.List; public class ForeachCollectionExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Carol"); for (String name : names) { System.out.println("Name: " + name); } } }
In this example, the foreach loop iterates over the names
ArrayList, assigning each element to the variable name
in each iteration.
While the foreach loop is a useful tool for simplifying iteration over arrays and collections, it has some limitations:
In conclusion, the foreach statement (enhanced for loop) in Java provides a more concise and readable way to iterate over arrays and collections. However, it has some limitations that make it unsuitable for certain situations where you need more control or need to modify the underlying data structure during iteration.
Enhanced for loop in Java examples
The enhanced for loop simplifies iteration through arrays or collections.
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println("Element: " + num); }
Iterating through arrays with foreach in Java
Use the enhanced for loop to iterate through elements in an array.
String[] fruits = {"Apple", "Banana", "Orange"}; for (String fruit : fruits) { System.out.println("Fruit: " + fruit); }
Using foreach for collections in Java
The enhanced for loop is handy for iterating through collections like ArrayList.
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5); for (int num : numbersList) { System.out.println("Number: " + num); }
Custom objects and foreach loop in Java
You can use the enhanced for loop for custom objects.
class Person { String name; Person(String name) { this.name = name; } } List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob")); for (Person person : people) { System.out.println("Person: " + person.name); }
Breaking from foreach loop in Java
To exit the enhanced for loop prematurely, use a labeled break statement.
int[] numbers = {1, 2, 3, 4, 5}; outerLoop: for (int num : numbers) { if (num == 3) { break outerLoop; // Exit the loop when num is 3 } System.out.println("Number: " + num); }
Modifying elements during foreach loop in Java
You can modify elements in a collection during iteration, but it's safer to use an iterator.
List<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); for (int i = 0; i < numbersList.size(); i++) { int num = numbersList.get(i); numbersList.set(i, num * 2); } // Alternatively, using iterator Iterator<Integer> iterator = numbersList.iterator(); while (iterator.hasNext()) { int num = iterator.next(); iterator.remove(); // Remove current element numbersList.add(num * 2); // Add modified element }
Using forEach in Java 8 for functional-style iteration
Java 8 introduces the forEach method for collections, allowing functional-style iteration.
List<String> fruits = Arrays.asList("Apple", "Banana", "Orange"); fruits.forEach(fruit -> System.out.println("Fruit: " + fruit));