Skip to main content

Java foreach Loop Examples - Complete Guid

Java foreach Loop Examples - Complete Guide

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:

  • Type is the data type of the elements
  • variable is the iteration variable
  • collection is 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!
    }
}

© 2025 Java Programming Blog. All rights reserved.

Comments

Popular posts from this blog

PHP Array Push Multiple Values: A Complete Guide | StackCodee

PHP Array Push Multiple Values: A Complete Guide | StackCodee PHP Array Push Multiple Values: A Complete Guide 📅 November 8, 2025 ⏱️ 8 min read 🏷️ PHP, Arrays, Programming Welcome to StackCodee, your go-to resource for practical programming knowledge. In this comprehensive guide, we'll explore the various methods to push multiple values to a PHP array efficiently. Whether you're a beginner or an experienced developer, understanding these techniques will enhance your array manipulation skills in PHP. Understanding PHP Arrays PHP arrays are incredibly versatile data structures that can hold multiple values of different types. They can be indexed numerically or associatively with key-value pairs, and they can even function as lists, stacks, or queues. ...

PHPMyAdmin Localhost:8080 Setup Guide

PHPMyAdmin Localhost:8080 Setup Guide PHPMyAdmin Localhost:8080 Setup Guide Learn how to install, configure, and troubleshoot PHPMyAdmin running on localhost port 8080 with detailed examples and solutions to common problems. ⏱️ 10 min read 🏷️ PHPMyAdmin, MySQL, Localhost, Web Development Installation Steps 1 Install PHPMyAdmin Download and install PHPMyAdmin on your local server environment (XAMPP, WAMP, MAMP, or manual setup). # For Ubuntu/Debian systems sudo apt-get install phpmyadmin # For CentOS/RHEL systems sudo yum install phpmyadmin # Or download direc...

Mastering PHP's array_merge(): When to Use It (And When Not To)

Pros, Cons, and Best Practices PHP's  array_merge()  function is one of the most commonly used array functions in web development. Whether you're building a simple website or a complex web application, understanding how to effectively merge arrays can save you time and prevent headaches. In this comprehensive guide, we'll explore everything you need to know about  array_merge() , including its advantages, limitations, practical use cases, and alternatives. What is  array_merge()  in PHP? array_merge()  is a built-in PHP function that combines two or more arrays into a single array. The function takes multiple array arguments and returns a new array containing all the elements from the input arrays. Basic Syntax php array_merge ( array ... $arrays ) : array Simple Example php $array1 = [ 'a' , 'b' , 'c' ] ; $array2 = [ 'd' , 'e' , 'f' ] ; $result = array_merge ( $array1 , $array2 ) ; print_r ( $result ) ; /* O...