What are the advantages of for-each loop?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What are the advantages of for-each loop??

In java, for each loop is the enhance version of for loop.

6th Feb 2019, 3:54 AM
Aazad Waf 🌀
Aazad Waf 🌀 - avatar
2 Answers
+ 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.
6th Feb 2019, 5:59 AM
HAS|B
HAS|B - avatar
0
According to SL, it makes the code easier to read and prevents bugs. https://www.sololearn.com/learn/Java/2209/?ref=app
6th Feb 2019, 6:01 AM
Lambda_Driver
Lambda_Driver - avatar