For Each Loop in Java
In Java, the for-each
loop (also known as the enhanced for loop) is a control flow statement that allows you to iterate over the elements of an array or a collection without having to use an index variable. It is called a "for-each" loop because it allows you to iterate over each element in the array or collection, one element at a time.
Here is the basic syntax for a for-each
loop in Java:
for (type element : array or collection) {
// code to be executed
}
The type
is the type of the elements in the array or collection, and the element
is a variable that represents each element in the array or collection as the loop iterates over it. The array or collection
is the array or collection that you want to iterate over.
Here is an example of a for-each
loop in Java that iterates over an array of strings and prints out the value of each element:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] words = {"apple", "banana", "cherry"};
for (String word : words) {
System.out.println(word);
}
}
}
Output:
apple
banana
cherry
This code defines an array of strings and then uses a for-each
loop to iterate over the elements of the array. The loop prints out the value of each element as it iterates over the array.
The output of this code will be the words “apple”, “banana”, and “cherry”, each on a separate line.
The for-each
loop is a useful control flow statement in Java, particularly when you need to iterate over the elements of an array or collection and you do not need to use an index variable. It is simple and easy to use, and it can make your code more readable and concise.
Find out more about Java here: