Can anyone please explain the difference between for and enhanced for loop in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Can anyone please explain the difference between for and enhanced for loop in java?

5th Oct 2017, 5:32 PM
Animesh Singh
Animesh Singh - avatar
4 Answers
+ 13
for loop: for(int i=0; i <arr.length; i++) { //code}; enhanced for loop: for(int i:arr) { //code}; enhanced for loop on Collection classes: list.forEach( //code ); Basically the difference is that you don't have to take care of the condition that stops the loop. Enhanced loops loop over the whole collection, unless you state a break or other exit condition in the // code block.
5th Oct 2017, 5:38 PM
Tashi N
Tashi N - avatar
+ 10
u answer all questions fast 😅 👏👏👏
5th Oct 2017, 7:16 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 3
Gotcha! Ty!@Tashi N
5th Oct 2017, 7:22 PM
Animesh Singh
Animesh Singh - avatar
+ 1
Also important to note is that you can't initialize arrays nor modify their elements with an enhanced for. An enhanced for can't be used to delete or remove the elements of a collection, because the enhanced for loop practically hides the iterator used to go through the elements of collections. And also, you can't use a single for-each to iterate over multiple collections or arrays.
5th Oct 2017, 11:18 PM
Ivan Lazarevski
Ivan Lazarevski - avatar