• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Enhanced for-loop problem

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Deepak,

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

Mihai Fonoage
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what mihai said is true
 
Ranch Hand
Posts: 2908
1
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 !
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
check out

https://coderanch.com/t/269503/java-programmer-SCJP/certification/Arrays
 
Deepak Bajoria
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hats off to this forum......I find all questions I stuck upon has already been discussed here. Great site.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic