• Post Reply Bookmark Topic Watch Topic
  • New Topic

In which situation should I use For loop and when enhanced for loop? both results same.  RSS feed

 
Sharmistha Sarkar
Ranch Hand
Posts: 50
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While writing a program, in which situation should I use For loop and when to use enhanced for loop? both results same. Is there any situation anyone ever faced ;when you could not get the result using for loop and had to use enhanced for loop or vice versa?
 
Tim Cooke
Marshal
Posts: 4051
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important difference between them is that for a regular loop you have to manage the array index yourself and in an 'enhanced' for loop, or 'foreach' loop, you do not.

So you might use a regular for loop if knowing the index is important to you in some way. As an example, if you wanted to print out every other item in a list then a regular for loop would make more sense for that.

 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think there is an even bigger difference. In the old for loop you are able to assign to array elements; in a for‑each loop (=enhanced for) the array/List/Collection/Set is regarded as read‑only.

Another difference is that it is easier to use an old for loop to iterate part of an array. Printing every other element, as Tim showed, is an example of iterating part of an array.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oracle's answer to this question is: (<= click that link for full info)
Oracle documentation wrote:
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

 
Sharmistha Sarkar
Ranch Hand
Posts: 50
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone. Jesper de Jong has cleared the doubt well.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!