Hi,
If you do the following
int arr[] = {1,2,3,4};
for(int i : arr){
// line 1
System.out.println(i);
System.out.println("arr=" + arr[i]);
arr[i]=0;
}
On first iteration
i = 1;
a[i] = 0 => a[1] = 0 => arr = {1,0,3,4}
On second iteration
i = 0;
a[i] = 0 => a[0] = 0 => arr = {0,0,3,4}
On third iteration
i = 3
a[i] = 0 => a[3] = 0 => arr = {0,0,3,0} //this is the step tht prevents the OutOfBoundsexcetion
On forth iteration
i = 0
a[i] = 0 => a[4] = 0 => arr = {0,0,3,0}
This was tricky...I hope the above helps...
Thanks,
Megha