+ 5
Can anyone please explain the difference between for and enhanced for loop in java?
4 odpowiedzi
+ 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.
+ 10
u answer all questions fast 😅
👏👏👏
+ 3
Gotcha! Ty!@Tashi N
+ 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.