Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The for statement provides a compact way to iterate over a range of values. The general form of thefor
statement can be expressed like this:Thefor (initialization; termination; increment) { statement }initialization
is an expression that initializes the loop-it's executed once at the beginning of the loop. Thetermination
expression 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,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
, uses afor
statement 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
for
loop. The scope of this variable extends from its declaration to the end of the block governed by thefor
statement so it can be used in the termination and increment expressions as well. If the variable that controls afor
loop is not needed outside of the loop, it's best to declare the variable in the initialization expression. The namesi
,j
, andk
are often used to controlfor
loops; declaring them within thefor
loop 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.