How to use Enhanced for Loop?
Using the following link to learn what the Enhanced for Loop is(The For-Each Loop). The following code is an interesting example of using Enhanced for Loop. The enhanced for loop will go through the array arr and set i to each member of the "int" array.
class Program {
public static void main(String[] args) {
int []arr = {1,2,3,4};
for ( int i : arr ) {
arr[i] = 0;
}
for ( int i : arr ){
System.out.println(i);
}
}
}
Why it output : 0030? Let's take a look:
int []arr = {1,2,3,4};
for ( int i : arr ) {
arr[i] = 0;
}
- Step 1. On the first iteration,
iwill be 1 becausearr[0]=1, and setarr[1]to 0. - Step 2. On the second iteration,
iwill be 0 becausearr[1]=0set by Step 1., and setarr[0]to 0. - Step 3. On the third iteration,
iwill be 3 becausearr[2]=3, and setarr[3]to 0. - Step 4. On the last iteration, i will be 0 because
arr[3]=0set by Step 3, and set arr[0] to 0.
Here is another sample code using "Enhanced For Loop" for multi-dimensional arrays:
class Program {
...
static void useEnhancedFor(int x[][]) {
for(int[] l:x) {
for(int m:l) {
System.out.print(m+" ");
}
}
System.out.println();
}
}
Most Recent java Faqs
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?
- What is runtime polymorphism in Java?
- How to add BASIC Authentication into HttpURLConnection?
- What is String literal pool?
- Can the run() method be called directly to start a thread?
- How to read input from console (keyboard) in Java?
- What does Class.forname method do?