|
|
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
forstatement 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 theforstatement can be expressed as follows.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 tofor (initialization; termination; increment) { statement(s) }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
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 ispublic 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 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.
In the Java programming language, version 5.0, a new kind offorstatement 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 from
ForDemo.
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(); } }forstatement in the preceding snippet like this: For eachint elementinarrayOfInts...Where the enhanced
forstatement really shines is when it's used with collections (classes that implement theCollectioninterface). Here's an old-fashioned
forstatement 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 the Genericssection and the Collections
chapter, respectively. The point is you can avoid it in the
forloop by using the enhancedforstatement.When you nest iterators, the enhanced//This is much prettier. void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel(); }forstatement is even nicer because you can avoid more unnecessary code; here's an example.The enhancedfor (Suit suit : suits) { for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank)); }forstatement doesn't work everywhere, unfortunately. If you need access to array indexes, for instance, enhancedforwon't work. However, using enhancedforstatements wherever possible can reduce certain kinds of bugs, and it makes the code look cleaner.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.