• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Enhanced for-loop problem

 
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
 
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
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what mihai said is true
 
Ranch Hand
Posts: 2908
1
Spring Java 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 !
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Hats off to this forum......I find all questions I stuck upon has already been discussed here. Great site.
 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic