java foreach


In Java, the for-each loop (also known as the enhanced for loop) is a loop that is used to iterate over the elements of an array or a collection. It is a concise and easy-to-use loop that allows you to iterate over the elements of a collection without the need to use an index or a counter variable.

Here is an example of how to use the for-each loop in Java:

// Create an array of integers
int[] numbers = { 1, 2, 3, 4, 5 };

// Iterate over the array using the for-each loop
for (int number : numbers) {

This code creates an array of integers and then uses the for-each loop to iterate over the elements of the array. It prints each element to the console.

The for-each loop has the following syntax:

for (type element : array) {
  // statements

The type parameter specifies the type of the elements in the array or collection, and the element parameter represents each element in the collection as it is being iterated over. The array parameter is the array or collection that you want to iterate over.

The for-each loop is particularly useful when you just want to perform a simple operation on each element of a collection, such as printing it to the console or adding it to a total.

For more information on the for-each loop in Java, you can refer to the Java documentation: