This week's book giveaway is in the Java in General forum.
We're giving away four copies of Event Streams in Action and have Alexander Dean & Valentin Crettaz on-line!
See this thread for details.
Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

For each loop confusing

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The output I got was
2
0
0.

Bu I don't understand how I get it. Please explain.
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Gautham Muralidharan wrote:Bu I don't understand how I get it. Please explain.


You could add a few additional println statements to see what's going on in the first enhanced for loop (as the second one should be pretty straightforward).

For example it could be something like:

Hope it helps!
Kind regards,
Roel
 
Gautham Muralidharan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the idea Roel. Now I found it.



This is equivalent to


where x will 0,1,2 in each iteration.


As the integer array is not initialized array[x] will always be 0 when x=1 and x=2, which means array[array[x]]=array[0] when x=1 and x=2. So in each iteration, array[0] is assigned with c++, which makes it 2 and the remaining two elements remain zero.
 
Bartender
Posts: 1244
86
Hibernate jQuery Eclipse IDE Angular Framework Spring MySQL Database AngularJS Tomcat Server Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes correct but remember integer ( Integer ) and int are different.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!