Java From Beginner To Advanced

0% completed

Previous
Next
Java for-each Loop

The for-each loop in Java provides a simple way to iterate over elements of an array or a collection. It is designed to reduce the verbosity of code when you need to access each element sequentially. This loop is ideal when you don’t need to modify the elements or use the index for any computation.

Syntax

for (type variable : collection) { // Code block to execute for each element }
  • type: The data type of the elements in the array or collection.
  • variable: A temporary variable that holds the current element in the iteration.
  • collection: The array or collection to be iterated over.

Execution Flow of for-each Loop

  • Iteration Start: The for-each loop starts at the first element of the array or collection.
  • Assignment: In each iteration, the current element is assigned to the variable.
  • Code Execution: The code inside the loop executes with the variable holding the current element.
  • Iteration Ends: This process repeats until every element in the array or collection has been processed.

Example 1: Iterating Over an Array

Below is an example that uses a for-each loop to print all elements in an integer array.

Java
Java

. . . .

Explanation:

  • The array numbers contains five integer elements.
  • The for-each loop iterates over each element in the array, assigning it to the variable num.
  • In each iteration, the current number is printed.

Example 2: Iterating Over a Collection (ArrayList)

Below is an example that uses a for-each loop to iterate over an ArrayList of strings and print each element.

Java
Java

. . . .

Explanation:

  • An ArrayList named fruits is created and populated with three string elements.
  • The for-each loop automatically iterates over each element in the ArrayList, assigning each to the variable fruit.
  • Each fruit in the list is printed to the console.

The for-each loop simplifies the process of iterating over arrays and collections by eliminating the need for explicit index management.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next