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
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?