|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The for
PENDING: This page will also discuss the for-each language feature introduced in 5.0. An example is here:ForEachDemo. Compare it to its functional equivalent,
ForDemo. Until this page is updated, see the 5.0 guide document The For-Each Loop
.
statement provides a compact way to iterate over a range of values. The general form of the
forstatement can be expressed like this:Thefor (initialization; termination; increment) { statement(s) }initializationis an expression that initializes the loop—it's executed once at the beginning of the loop. Theterminationexpression determines when to terminate the loop. When the expression evaluates tofalse, 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
forloops are used to iterate over the elements in an array or the characters in a string. The following sample,ForDemo, uses a
forstatement (shown in boldface) to iterate over the elements of an array and to print them:The output of the program is: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(); } }32 87 3 589 12 1076 2000 8 622 127.Notice that you can declare a local variable within the initialization expression of a
forloop. 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 namesi,j, andkare often used to controlforloops; declaring them within theforloop initialization expression limits their life span and reduces errors.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.