Java Reference
In-Depth Information
The Enhanced
for
Loop
In Java 5.0, a new
for
loop was introduced called the
enhanced
for
loop (also called
a
for-each
loop
). The following code demonstrates the syntax of a
for-each
loop
by iterating through the
july
array and displaying each of the 31
GregorianCalendar
objects:
for(GregorianCalendar day : july) {
System.out.print(day.get(Calendar.MONTH) + “/”
+ day.get(Calendar.DAY_OF_MONTH) + “/”
+ day.get(Calendar.YEAR) + “ “);
}
This enhanced
for
loop is read “for each
day
in
july
”, where
day
is of type
GregorianCalendar
. The enhanced
for
loop can also be used for iterating through many
of the data structures found in the
java.util
package. We discuss these data structures
along with the enhanced for loop in more detail in Chapter 3, “Flow Control.”
Let's look at an example to demonstrate some of the details of working with arrays.
Study the following
ArrayDemo
program and determine if it compiles and what its output is.
In addition, try to determine when the array object on line 3 becomes eligible for garbage
collection.
1. public class ArrayDemo {
2. public static void main(String [] args) {
3. double [] cubics = new double[10];
4. for(int i = 0; i < cubics.length; i++) {
5. int value = i + 1;
6. cubics[i] = value * value * value;
7. }
8.
9. double [] temp = cubics;
10. temp[5] = -1;
11. System.out.println(cubics[5]);
12. cubics = null;
13. for(double a : temp) {
14. System.out.print(a + “ “);
15. }
16.
17. temp = new double[20];
18. }
19.}
Search WWH ::
Custom Search