Java Reference
In-Depth Information
Note Enhanced for loops allow automatic iteration over arrays and other
iterable objects.
Here's a second example using strings instead of ints. It follows the same pattern as before, “For
each string in the nameList array, print that string.”
String[] nameList = {"Adam Brown","Betsy Dudley","Carl Frank"};
for (String name: nameList){
System.out.println(name);
}
Enhanced for loops offer the same functionality of regular for loops with a format that's easier to
code and read. They do require a data structure that's iterable, but if you are working with arrays,
they may provide a handy solution for you.
try It Out: an enhanced for Loop
try it out
 To create an enhanced for loop, follow these steps:
1. Create a new class named EnhancedForLoop , following the process you learned about earlier. You
can continue to use the same Chapter5 project. Create a new class by right-clicking on the src
folder in your project. Select New and then Class.
2. In the Name field, enter the name of your class, EnhancedForLoop , beginning with a capital letter
by Java convention. In the bottom portion of the New Java Class window, there is a section that
reads: “Which method stubs would you like to create?” You may choose to check the box next to
public static void main(String[] args) ” to automatically create a main method.
3. You should automatically have the basis for the class body shown here:
public class EnhancedForLoop {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
If not, you can type it yourself. You do not need the comments, which are denoted with /** or // .
In Eclipse, they will appear as blue or green text. Comments are useful for explaining what the
code is doing, but are never compiled or executed by Java.
public class EnhancedForLoop {
public static void main(String[] args){
}
}
Search WWH ::




Custom Search