站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

The for Statement - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

The for Statement

The for (in the glossary) statement provides a compact way to iterate over a range of values. The for statement has a general form and, as of version 5.0, an enhanced form that can be used when performing simple iterations over arrays and collections. The general form of the for statement can be expressed as follows.
for (initialization; termination; increment) {
    statement(s)
}
The initialization expression initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets invoked after each iteration through the loop. All these components are optional. In fact, to write an infinite loop, you omit all three expressions.
for ( ; ; ) {    //infinite loop
    ...
}

Often for loops are used to iterate over the elements in an array or the characters in a string. The following sample, ForDemo (in a .java source file), uses a for statement (shown in boldface) to iterate over the elements of an array and to print them.

public class ForDemo {
    public static void main(String[] args) {
        int[] arrayOfInts = { 32, 87, 3, 589, 12, 
                              1076, 2000, 8, 622, 127 };

        for (int i = 0; i < arrayOfInts.length; i++) {
            System.out.print(arrayOfInts[i] + " ");
        }
        System.out.println();
    }
}
The output of the program is 32 87 3 589 12 1076 2000 8 622 127.

Notice that you can declare a local variable within the initialization expression of a for loop. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for loop is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the for loop initialization expression limits their life span and reduces errors.

Iterating over Collections and Arrays with Enhanced for

In the Java programming language, version 5.0, a new kind of for statement was created especially for collections and arrays. Here's some code, taken from ForEachDemo (in a .java source file), that does the same thing as the previous code snippet, which was taken from ForDemo (in a .java source file).
public class ForEachDemo {
    public static void main(String[] args) {
        int[] arrayOfInts = { 32, 87, 3, 589, 12,
                              1076, 2000, 8, 622, 127 };

        for (int element : arrayOfInts) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
}
You can read the for statement in the preceding snippet like this: For each int element in arrayOfInts...

Where the enhanced for statement really shines is when it's used with collections (classes that implement the Collection (in the API reference documentation) interface). Here's an old-fashioned for statement that iterates through a collection.

//This is ugly. Avoid it by using enhanced for!
void cancelAll(Collection<TimerTask> c) {
    for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
        i.next().cancel();
}
Don't worry about the strange <TimerTask> bit of code for now. You'll learn about it and about collections in the Generics (in the Learning the Java Language trail) section and the Collections (in the Learning the Java Language trail) chapter, respectively. The point is you can avoid it in the for loop by using the enhanced for statement.
//This is much prettier.
void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}
When you nest iterators, the enhanced for statement is even nicer because you can avoid more unnecessary code; here's an example.
for (Suit suit : suits) {
    for (Rank rank : ranks)
        sortedDeck.add(new Card(suit, rank));
}
The enhanced for statement doesn't work everywhere, unfortunately. If you need access to array indexes, for instance, enhanced for won't work. However, using enhanced for statements wherever possible can reduce certain kinds of bugs, and it makes the code look cleaner.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.