Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Understanding foreach loop in Java

[post-views]

 

In this lesson, you will learn.

  • Working with a for-each loop in Java

 

Working with a for-each loop in Java

  • The foreach loop in Java, also known as the enhanced for loop was introduced in Java 5.
  • It provides a simpler way to iterate over collections (like arrays or any other objects that implement the Iterable interface) compared to the classic for loop.

 

What is an Iterable Interface

The Iterable interface in Java is a part of the Java Collections Framework which includes classes such as

  • Lists: ArrayList, LinkedList, etc.
  • Sets: HashSet, LinkedHashSet, TreeSet, etc.
  • Queues: PriorityQueue, LinkedList (also a List), etc.

 

Note: You will learn Java Collection in the upcomming chapters.

 

Syntax of a for-each Loop

for (Type var : collection) {
    // Block of statements
}

 

  • Type: Elements’ type contained in the collection or array you’re iterating over.
  • var: Variable that represents the current element in the collection or array during each iteration of the loop.
  • collection: The collection or array you want to iterate over. This can be any object that implements the Iterable interface or an array.

 

Example 1: Iterating Over Array of Integers

package ch5;

public class ForEachExample1 {
	public static void main(String[] args) {
		
		int[] numbers = {1, 2, 3, 4, 5};
		for (int number : numbers) {
		    System.out.println(number);
		}
	}
}

 

Output

1
2
3
4
5

 

Example 2: Iterating Over an Array of Strings

package ch5;

public class ForEachExample2 {

	public static void main(String[] args) {
		String[] fruits = {"Apple", "Banana", "Cherry", 
				"Date", "Elderberry"};

		for (String fruit : fruits) {
		    System.out.println(fruit);
		}
	}
}

 

Output

Apple
Banana
Cherry
Date
Elderberry

 

For loop vs. for-each

Use Case

  • For Loop: It’s typically used when you need precise control over the iteration process, such as when you need to iterate backward, skip certain items, or access the index of the elements.
  • Foreach Loop: It’s best used when you need to iterate through an array or collection and don’t need to modify the array/collection itself or need access to the index of the element being processed.

 

Performance

  • There’s generally not a significant difference in performance between the two loops.
  • However, the enhanced for loop can lead to slightly cleaner and more readable code when working with collections or arrays

 

 


End of the lesson….enjoy learning

 

Student Ratings and Reviews

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review