QUESTIONS & ANSWERS
JAVA
Explain for-each loop in Java.
In Java, a for-each loop (also known as an enhanced for loop) is a convenient way to iterate over elements in a collection or an array. It is especially useful when you want to process all the elements in a collection or array in a sequential order.
The syntax for a for-each loop in Java is:
for (data_type variable : collection) {
// code block to be executed
}
Here, data_type
is the type of data stored in the collection or array, variable
is a new variable that will be declared in each iteration and will store the current element, and collection
is the name of the collection or array to be iterated over.
For example, if you have an array of integers int[] numbers = {1, 2, 3, 4, 5};
, you can use a for-each loop to iterate over its elements as follows:
for (int number : numbers) {
System.out.println(number);
}
Output:
1
2
3
4
5