0
What are the advantages of for-each loop??
In java, for each loop is the enhance version of for loop.
2 Antworten
+ 2
For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5.
⚫️It starts with the keyword for like a normal for-loop.
⚫️Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
⚫️In the loop body, you can use the loop variable you created rather than using an indexed array element.
⚫️It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
source: geeksforgeeks
for each loop is used to read the elements of an array, it is the enhance version of for loop.
Syntax:
// for each
for (type var : array)
{
statements using var;
}
is equivalent to:
// normal for
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
the main advantage of enhanced for is readability.
0
According to SL, it makes the code easier to read and prevents bugs.
https://www.sololearn.com/learn/Java/2209/?ref=app