Enhanced for Statement

In previous examples, we demonstrated how to use counter-controlled for statements to iterate through the elements in an array. In this section, we introduce a feature new in J2SE 5.0the enhanced for statement, which iterates through the elements of an array or a collection without using a counter. This section discusses how to use the enhanced for statement to loop through an array. We show how to use the enhanced for statement with collections in Chapter 19, Collections. The syntax of an enhanced for statement is:


       for ( parameter : arrayName )
          statement

where parameter has two partsa type and an identifier (e.g., int number), and arrayName is the array through which to iterate. The type of the parameter must match the type of the elements in the array. As the next example illustrates, the identifier represents successive values in the array on successive iterations of the enhanced for statement.

Figure 7.12 uses the enhanced for statement to calculate the sum of the integers in an array of student grades (lines 1213). The type specified in the parameter to the enhanced for is int, because array is an array containing int valuestherefore, the loop will select one int value from the array during each iteration. The enhanced for statement iterates through successive values in the array one-by-one. The enhanced for header can be read concisely as "for each iteration, assign the next element of array to int variable number, then execute the following statement." Thus, for each iteration, identifier number represents an int value in array. Lines 1213 are equivalent to the following counter-controlled repetition used in lines 1213 of Fig. 7.5 to total the integers in array:


 

for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ];

 

Figure 7.12. Using the enhanced for statement to total integers in an array.

 1 // Fig. 7.12: EnhancedForTest.java
 2 // Using enhanced for statement to total integers in an array.
 3
 4 public class EnhancedForTest
 5 {
 6 public static void main( String args[] )
 7 {
 8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
 9 int total = 0;
10
11 // add each element's value to total
12 for ( int number : array ) 
13  total += number; 
14
15 System.out.printf( "Total of array elements: %d
", total );
16 } // end main
17 } // end class EnhancedForTest
 
Total of array elements: 849
 

The enhanced for statement simplifies the code for iterating through an array. Note, however, that the enhanced for statement can be used only to access array elementsit cannot be used to modify elements. If your program needs to modify elements, use the traditional counter-controlled for statement.

The enhanced for statement can be used in place of the counter-controlled for statement whenever code looping through an array does not require access to the counter indicating the index of the current array element. For example, totalling the integers in an array requires access only to the element valuesthe index of each element is irrelevant. However, if a program must use a counter for some reason other than simply to loop through an array (e.g., to print an index number next to each array element value, as in the examples earlier in this chapter), use the counter-controlled for statement.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net