Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Arrays Iteration Ye Olde Unenhanced For Loop

A question about this video

Hi, I find the unenhanced for loop to be better when we want to output a elements index number and the element itself like?:

System.out.printf("%d : %s", i+1, something[i]

how do we even do it in the enhanced for loop?

in some cases the enhanced for loop is better and is some cases the other am i right?

Eric McKibbin

2 Answers


Eric M
Eric M
11,545 Points

Hi noob,

You're right that you should use the loop that's more appropriate to your task and that you can't print the index with the enhanced for loop (that I'm aware of).

Generally if you don't need to work with the index directly the enhanced for loop is a better choice for iterating over a collection, but as you've pointed out that's not the only use of loops.



Edit: Thinking about this a bit more if you're working with an object that has an [object].IndexOf([stored-item]) method you could use that, but it's probably more expensive than just using a plain for (;;) loop.