0% completed
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.
for (type variable : collection) { // Code block to execute for each element }
Below is an example that uses a for-each loop to print all elements in an integer array.
Explanation:
numbers
contains five integer elements.num
.Below is an example that uses a for-each loop to iterate over an ArrayList
of strings and print each element.
Explanation:
ArrayList
named fruits
is created and populated with three string elements.ArrayList
, assigning each to the variable fruit
.The for-each loop simplifies the process of iterating over arrays and collections by eliminating the need for explicit index management.
.....
.....
.....