for loop index modificationn

Don’t use a for loop with an index (or counter) variable if you can replace it with the enhanced for loop (since Java 5) or forEach (since Java 8). It’s because the index variable is error-prone, as we may alter it incidentally in the loop’s body, or we may starts the index from 1 instead of 0.
Consider the following example that iterates over an array of Strings:
String[] names = {"Alice", "Bob", "Carol", "David", "Eric", "Frank"};
for (int i = 0; i < names.length; i++) {
As you can see, the index variable i in this for loop can be altered incidentally which may cause unexpected result. We can avoid potential problems by using an enhanced for loop like this:
for (String aName : names) {
This does not only remove potential issues but also make the code cleaner and more succinct. 

Open in new window

how is it possible to do for loop index modifycation?

how enhanced for loop is diferent from for each loop?

is there any case where we still has to use traditional for loop with index
please advise
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jeffrey Dake Senior Director of TechnologyCommented:
The enhanced for loop is really for short hand just to make the code a little easier to read, and you don't have to worry about off by one errors.  There is nothing technically wrong with the first way you did it,  but readability of code is pretty important, especially when another developer comes around and tries to read it.

As for using the old way of for loops, you still may have to use it from time to time.  The enhanced for loop works on Collections, but it does not work on all data types.  You may still run across something, or build something, that you need to loop through that is not a Collection.  This is when you would switch back to the older style, so it is still good to know how to do both ways.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
System Programming

From novice to tech pro — start learning today.