Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enhanced for-loop problem

 
Deepak Bajoria
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mihai Fonoage
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deepak,

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

Mihai Fonoage
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what mihai said is true
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry folks, I am not able to find out that already discussed thread, Please anybody put some pointer to that thread !
 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check out

http://www.coderanch.com/t/269503/java-programmer-SCJP/certification/Arrays
 
Deepak Bajoria
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hats off to this forum......I find all questions I stuck upon has already been discussed here. Great site.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic