What is For-each loop in Java?

In Java, the for-each loop, also known as the enhanced for loop, is a convenient way to iterate over elements in an array or a collection. It is a simplified way of iterating through a collection compared to traditional for loops.

The syntax of the for-each loop is as follows: 

 

for (elementDataType element : collection) {
    // code to be executed for each element
}

Here, elementDataType is the data type of the elements in the collection, and element is a variable that represents each element in the collection. The collection is the array or collection that is being iterated over.

For example, to iterate through an array of integers using a for-each loop, you could use the following code: 

 

int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
    System.out.println(number);
}

This code would print out each number in the array on a new line.

The for-each loop is useful for iterating through collections and arrays because it simplifies the code and makes it easier to read. It also helps to avoid common mistakes that can be made with traditional for loops, such as off-by-one errors.

Submit Your Programming Assignment Details