This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enhanced Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enhanced Loop" Watch "Enhanced Loop" New topic

Enhanced Loop

Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
I would like to know the working of Enhanced loop in a simple method.
I did understand it once but then i forgot
Does any one has a simple way so i can understand it and that it stays in my brain!?!
There were various posts on it, but i can't find it.
If some one has the link please pass it on.

This was a small code i wrote.
I can't understand the second part of the result.

The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Santhosh Kumar
Ranch Hand

Joined: Nov 07, 2000
Posts: 242
Enhanced for loop does one and only one thing, looping through all elements of an given array or Iterable object.

It is like, saying "for each object in the given array or iterable object, do something". While looping through the array or Iterable object, assigns the currently positioning element into given variable so that you access the element in the loop body.

Back to your code:

In the first loop, you are looping through the array and printing the array values.

In the second loop, you are looping through the array, using the values as index to select the array values.

First iteration, var i would be "9" and so array value at position "9" is "0"; That's what you are printing.
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
Ohh Thanks!

Looks like i was thinking more then i should!!

There was a post about some mock question which used an Enhaced Loop and where the result was 0030 or something of that sort.
Ther was a long discussion on it.

Actually there were 2 posts on it.

Doesn any one has a link to it?
Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

Hey I don't know where that post is but the code was this

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
Thanks Ankit!
I agree. Here's the link:
subject: Enhanced Loop
It's not a secret anymore!