|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The forstatement 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 }initializationis an expression that initializes the loop-it's executed once at the beginning of the loop. Theterminationexpression determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates tofalse, the loop terminates. Finally,incrementis 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 to iterate over the elements of an array and 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.Note 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 theforstatement so it can be used in the termination and increment expressions as well. If the variable that controls aforloop 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-2004 Sun Microsystems, Inc. All rights reserved.