for loop index modificationn

gudii9
gudii9 used Ask the Experts™
on
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:
1
2
3
4
5
String[] names = {"Alice", "Bob", "Carol", "David", "Eric", "Frank"};
 
for (int i = 0; i < names.length; i++) {
    doSomething(names[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:
1
2
3
for (String aName : names) {
    doSomething(aName);
}
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Director of Technologyy
Commented:
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial