permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enhanced for-loop problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enhanced for-loop problem" Watch "Enhanced for-loop problem" New topic

Enhanced for-loop problem

Deepak Bajoria
Ranch Hand

Joined: Mar 07, 2008
Posts: 39
Hello Ranchers,

This code:

compiles successfully produces the output:

I am totally puzzled about it.

As per my understanding...In the first loop values of i is set to 1,2,3,and 4. Therefore it tries to access these the positions: arr[1],arr[2],arr[3]and arr[4]. But when it tries to access arr[4] it should throw ArrayIndexOutOfBoundsException because arr has only 4 elements.

Even if it could access them, the output should have been 0 0 0 0 and not 0 0 3 0 as they all are being set to 0 in the 1st loop. From where does that 3 persists?


SCJP - 93%
My Blog
Mihai Fonoage
Ranch Hand

Joined: Feb 25, 2006
Posts: 39
Hi Deepak,

Please search this forum for the problem you mentioned has been already discussed in detail.

Mihai Fonoage
Milan Sutaria
Ranch Hand

Joined: Jul 10, 2008
Posts: 122
what mihai said is true

SCJP 6 83%
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2904

Sorry folks, I am not able to find out that already discussed thread, Please anybody put some pointer to that thread !

[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Pankaj Mittal
Ranch Hand

Joined: Jul 09, 2008
Posts: 32
check out

2008 SCJP(5.0) 88%
Deepak Bajoria
Ranch Hand

Joined: Mar 07, 2008
Posts: 39
Hats off to this forum......I find all questions I stuck upon has already been discussed here. Great site.
I agree. Here's the link:
subject: Enhanced for-loop problem
It's not a secret anymore!