Enhanced for loop in Java(for each) language
Enhanced for loop in Java(for each) language
In this tutorial, We will discuss Enhanced for loop in Java(for each) language.
Enhanced for loop is functioning like a normal for loop but it is used to iterates through items of the collection
Enhanced for loop is mostly used to display array or collection of the element instead of using for loop. It can use one D, Two D, Three D arrays. – The array is a collection of variables of the same type.
Syntax
for(data_type item:collection){ statement(s); }
How enhanced for loop works:
- Iterates through each item one by one in the given collection or array.
- Stores each item one by one in a variable to execute.
- The body of the for -each loop is executed.
Examples for enhanced for loop
program 1
Enhanced for loop with single dimension array in Java
class Enhanced_for{ public static void main(String args[]){ String[] names={"Mackal","Hari","Smith","Jhon","khan"}; //using for each loop for (String name:names){ System.out.println(name); } } }
When the above code is executed, it produces the following results:
Mackal Hari Smith Jhon Khan
program 1
Enhanced for loop with Two dimension array in Java
class Enhanced_for2d{ public static void main(String args[]){//declare a two dimension array in Java char[][] Alpabets={{'A','B','C','D'}, {'E','F','G','H'}, {'I','J','K','L'}}; //using for each loop for (char Alp[]:Alpabets){ for(char j:Alp){ System.out.println(j); } } } }
When the above code is executed, it produces the following results:
A B C D E F G H I J K L
Program 3
Enhanced for loop with Three dimension array in Java
class Enhanced_for3d{ public static void main(String args[]){ int[][][] numbers={ //declare a three dimension array in java {{1,2,3,4}, {5,6,7,8}}, { {9,10,11,12}, {13,14,15,16}, {17,18,19,20}}}; //using for each loop for (int i[][]:numbers){ for(int j[]:i){ for(int k:j){ System.out.println(k); } } } } }
When the above code is executed, it produces the following results:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Another example for enhance for loop
To calculate the sum of elements inĀ one dimension array
class Enhanced_forsum{ public static void main(String args[]){ int[] numbers={17,18,19,20,45,65,34};//single dimension array int total=0; //assign initialized total value as 0 //using for each loop for (int num:numbers){ total+=num; } System.out.println("Total is: "+total); } }
When the above code is executed, it produces the following results:
Total is : 218
There are other Java language post that is similar to the this post
Nested For loop in Java language
Nested For loop in C++ language
Nested For loop in C language
Nested For loop in Python language
Suggested for you
Single dimension array in Java