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. Thefor
statement has a general form and, as of 5.0, an enhanced form that you can use when performing simple iterations over arrays and collections. The general form of thefor
statement can be expressed like this:Thefor (initialization; termination; increment) { statement(s) }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. 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 (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
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.
In 5.0 a new kind offor
statement was created especially for collections and arrays. Here's some code, taken fromForEachDemo
, that does the same thing as the previous code snippet (which was taken fromForDemo
).You can read thepublic 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(); } }for
statement in the preceding snippet like this: For eachint element
inarrayOfInts
...Where the enhanced
for
statement really shines is when it's used with collections (classes that implement theCollection
interface). Here's an old-fashionedfor
statement that iterates through a collection:Don't worry about the strange//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(); }<TimerTask>
bit of code for now. You'll learn about it and about collections in Generics and Collections, respectively. The point is you can avoid it in thefor
loop by using the enhancedfor
statement, like this:When you nest iterators, the enhanced//This is much prettier. void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel(); }for
statement is even nicer because you can avoid more unnecessary code. For example:The enhancedfor (Suit suit : suits) { for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank)); }for
statement doesn't work everywhere, unfortunately. If you need access to array indexes, for example, enhancedfor
won't work for you. However, using enhancedfor
statements wherever possible can reduce certain kinds of bugs, and it makes your code look cleaner.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.