FAQ

Java

JSP

Servlet


Advertisement



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, i will be 1 because arr[0]=1, and set arr[1] to 0.
  • Step 2. On the second iteration, i will be 0 because arr[1]=0 set by Step 1., and set arr[0] to 0.
  • Step 3. On the third iteration, i will be 3 because arr[2]=3, and set arr[3] to 0.
  • Step 4. On the last iteration, i will be 0 because arr[3]=0 set 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();
}
}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |