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); }
program 1
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
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
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
How to find reverse number using method In this article, we will discuss the concept…
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…
C Program to multiplication table using Array In this tutorial , we will discuss about…