The enhanced for loop, also known as the for-each loop, is a type of loop in Java that makes it easy to iterate over elements in an array or other collections. The for-each loop can be used to iterate over an array in the following way:
dataType[] arrayName = {value1, value2, ..., valueN};
for (dataType element : arrayName) {
// code to be executed for each element
}
Here, dataType
is the data type of the elements in the array, arrayName
is the name of the array, and element
is a variable that represents each element in the array.
For example, to print all the elements in an array of integers, you can use the following code:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
This will output:
1
2
3
4
5
The for-each loop can also be used with other collections such as lists and sets. The main advantage of using the for-each loop is that it simplifies the syntax for iterating over elements in a collection and makes the code more readable. Additionally, it eliminates the possibility of errors in the indexing of elements, which can occur when using traditional for loops.