Java foreach Loop Examples: A Complete Guide
Published on: October 15, 2023 | Author: Java Expert | Category: Java Programming
Introduction to Java foreach Loop
The foreach loop, also known as the enhanced for loop, was introduced in Java 5. It provides a simpler way to iterate through collections and arrays compared to traditional for loops. In this guide, we'll explore various examples of using foreach loops in Java.
Basic Syntax of foreach Loop
The foreach loop has the following syntax:
for (Type variable : collection) {
// body of loop
}
Where:
Typeis the data type of the elementsvariableis the iteration variablecollectionis the array or collection to iterate through
Example 1: Iterating Through an Array
The most common use of foreach loop is to iterate through arrays:
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Using foreach loop to iterate through the array
for (int number : numbers) {
System.out.println("Number: " + number);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 2: Iterating Through a Collection
foreach loops work seamlessly with Java Collections:
import java.util.ArrayList;
import java.util.List;
public class ForEachCollection {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Using foreach loop with ArrayList
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}
Output:
Fruit: Apple
Fruit: Banana
Fruit: Orange
Fruit: Mango
Example 3: Iterating Through a String Array
foreach loops can also iterate through String arrays:
public class StringForEach {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
// Using foreach with String array
for (String name : names) {
System.out.println("Hello, " + name + "!");
}
}
}
Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
Hello, Diana!
Example 4: Using foreach with Custom Objects
You can use foreach loops with collections of custom objects:
import java.util.ArrayList;
import java.util.List;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class CustomObjectForEach {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("John", 20));
students.add(new Student("Emma", 22));
students.add(new Student("Michael", 21));
// Using foreach with custom objects
for (Student student : students) {
System.out.println("Student: " + student.getName() +
", Age: " + student.getAge());
}
}
}
Output:
Student: John, Age: 20
Student: Emma, Age: 22
Student: Michael, Age: 21
Example 5: Using foreach with Multidimensional Arrays
You can use nested foreach loops with multidimensional arrays:
public class MultiDimensionalForEach {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Using nested foreach loops
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
Limitations of foreach Loop
While foreach loops are convenient, they have some limitations:
- Cannot modify the collection structure (add/remove elements) during iteration
- Cannot access the index of the current element
- Cannot iterate backwards through a collection
- Cannot modify the array elements for primitive types
Example of what you cannot do:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
// This will throw ConcurrentModificationException
for (String item : list) {
if (item.equals("B")) {
list.remove(item); // Not allowed!
}
}
Comments
Post a Comment