Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,516 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.