When should you use the for-each loop?

When should you use the for-each loop? Anytime you can. It really beautifies your code. Unfortunately, you cannot use it everywhere.

Before starting about for-each loop I would like to discuss few things. When we talk about for-each then loop followings point raise in mind.

  • For-each is faster
  • Code looks beautiful
  • Performance is better
  • Its avoid iterator

Then why should not be used in everywhere ? 

My Another question is when we  use for and when we will use for-each.? How for each is faster over for loop. What is happening internally. Lets look into this

Iterator(for) is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection.

For each loop is meant for traversing items in a collection.

You are smart if you could know what is similar, but smarter people know what the differences are.

  • The only practical difference between for and foreach is that, in the case of indexable objects, you do not have access to the index
  • When accessing collections, a foreach is significantly faster than the basic for loop’s array access. When accessing arrays, however–at least with primitive and wrapper-arrays–access via indexes is dramatically faster.
So now come when my previous question when should you use the for-each loop? 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.