This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Enhanced For Loop

Arjun Reddy
Ranch Hand
Posts: 629
Hi Guys,

I wrote the following code:

And when I run it, It givin result as

2
3
4
5
at EnhancedForLoop.main(EnhancedForLoop.java:14)

It's basically taking i value from index 1 and not from index 0. Am I doing something wrong?

Thanks.

ramesh maredu
Ranch Hand
Posts: 210
try

for(int i:a)
{
System.out.println(i);
}

Arjun Reddy
Ranch Hand
Posts: 629
Thanks Ramesh. It worked.

ansuman mohapatra
Greenhorn
Posts: 27
even I m confused. Can any one clarify ?

and what does for(int i:a) does ??

Sagar Rohankar
Ranch Hand
Posts: 2907
1
even I m confused. Can any one clarify ?

and what does for(int i:a) does ??

The for each loop , iterate over array "a" and takes each array element into temp variable i , so "i" contains the elements of array "a" starting from index 0.

The for each loop just saves your few lines of code and puts some readability :
The above code is same as this simple for loop :

Here the loop iterate through "a" array ...
[ June 30, 2008: Message edited by: Sagar Rohankar ]

ansuman mohapatra
Greenhorn
Posts: 27
ok but why it doesnt start from index 0 ?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15568
46
It does, but the point is that i is not the index - it is the element of the array. Look carefully at what happens:

int[] a = { 1, 2, 3, 4, 5 };

First time in the loop: i = a[0] = 1 - Then you print out a[i] which is a[1] which is 2
Second time in the loop: i = a[1] = 2 - Then you print out a[i] = a[2] = 3
...
Fifth time in the loop: i = a[4] = 5 - Then you print out a[i] = a[5] -> ArrayIndexOutOfBoundsException because the array has only 5 members (a[0] to a[4]).

[ June 30, 2008: Message edited by: Jesper Young ]
[ June 30, 2008: Message edited by: Jesper Young ]

Bob Ruth
Ranch Hand
Posts: 320
Your enhanced for loop did start at element 0. Element 0 is equal to 1. So, on the very first loop, i wil be set to 1. The next statement is the print where you ask it to print the value of a[i]. What is i? 1! So you picked up a[0], which was a one, and printed a[1] which is a two.

Ranch Hand
Posts: 71
Hi Rancher ,

you are using a good loop in bad way.

Sagar Rohankar
Ranch Hand
Posts: 2907
1