File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enhanced for-loop problem" Watch "Enhanced for-loop problem" New topic
Author

Enhanced for-loop problem

Deepak Bajoria
Ranch Hand

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

This code:

compiles successfully produces the output:
0
0
3
0


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?


Thanks


SCJP 5 - 93%
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: 118
what mihai said is true


SCJP 6 83%
Working on SCWCD/OCPJWCD
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

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

http://www.coderanch.com/t/269503/java-programmer-SCJP/certification/Arrays


2008 SCJP(5.0) 88%
Deepak Bajoria
Ranch Hand

Joined: Mar 07, 2008
Posts: 35
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: http://aspose.com/file-tools
 
subject: Enhanced for-loop problem
 
Similar Threads
Arrays in for loop
for each
Why will I get this output?
for each loop and array
enhanced for loop problem -- from a mock