Beginning Programming with Java For Dummies, 6th Edition
Book image
Explore Book Buy On Amazon
You can make an enhanced for loop to step through a bunch of values, including an array’s values. Let’s take a look at an enhanced for loop that steps through an array’s values.

To see such a loop, start with this code. The loop looks something like this:

for (int roomNum = 0; roomNum < 10; roomNum++) {



To turn this into an enhanced for loop, you make up a new variable name. (What about the name howMany? Nice name.) Whatever name you choose, the new variable ranges over the values in the guestsIn array.

for (int howMany : guestsIn) {



This enhanced loop uses this format.

for (TypeName variableName : RangeOfValues) {



The RangeOfValues can belong to an enum type. Here, the RangeOfValues belongs to an array.

Enhanced for loops are nice and concise. But don’t be too eager to use enhanced loops with arrays. This feature has some nasty limitations. For example, the new howMany loop doesn’t display room numbers. Room numbers are avoided because the room numbers in the guestsIn array are the indices 0 through 9. Unfortunately, an enhanced loop doesn’t provide easy access to an array’s indices.

And here’s another unpleasant surprise. Start with the following loop:

for (int roomNum = 0; roomNum < 10; roomNum++) {

guestsIn[roomNum] = diskScanner.nextInt();


Turn this traditional for loop into an enhanced for loop, and you get the following misleading code:

for (int howMany : guestsIn) {

howMany = diskScanner.nextInt(); //Don't do this


The new enhanced for loop doesn’t do what you want it to do. This loop reads values from an input file and then dumps these values into the garbage can. In the end, the array’s values remain unchanged.

It’s sad but true. To make full use of an array, you have to fall back on Java’s plain old for loop.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a veteran author and educator. At the University of Illinois, he was named five times to the university-wide List of Teachers Ranked as Excellent by their Students. He has written several books on Java and Android development.

This article can be found in the category: