In Java, loops repeatedly perform coded instructions until the defined condition gets met. Generally, there are three types of loops in Java, for loop, while loop, and do…while loop. However, each needs a complex syntax with clearly defined variables, conditions, and actions (increment/decrement).
Table of Contents
The for-each, or enhanced for loop, cuts complexity down to size and enables us to deploy and implement loops faster. To define a for-each loop, only the variable and the array require definition, while the rest gets processed internally.
True that, for-each loops are not fit for times when more control over iterations is desired, yet they do the job at other times. So, without further ado, let’s explore how for-each loop or Java enhanced for loop works.
The for-each or enhanced for loop in Java helps developers apply the same conditional barriers with less hassle. Aptly named enhanced for loop, it does precisely what for loop does but takes less effort and time. They simplify what the for loops do, i.e., iterating through a collection or array of variables.
for (datatype variable : array) { // code to be executed }
In the above syntax, dataType specifies the array type; the variable implies a variable designated for each element during the iteration; the array defines where the function gets looped.
class ForEachExample { public static void main(String[ ] args) { int [ ] odd numbers = { 1, 3, 5, 7 }; for( int number : odd numbers) { System .out.println(number); } } }
1 3 5 7
The above syntax illustrates how for-each loop creates an array named odd_numbers. In the example above, Java enhanced for loop iterates and prints odd numbers in an array.
class ForEachExample { public static void main(String [ ] args) { int[ ] odd numbers = { 1, 3, 5, 7 }; for(int number : odd number){ number = number*3; System.out.printnl(number); } } }
3 9 15 21
// Calculate the sum of all elements of an array class Main { public static void main(String[] args) { // an array of numbers int[] numbers = {2, 6, 9, -7, 0, 15}; int sum = 0; // iterating through each element of the array for (int number: numbers) { sum += number; } System.out.println("Sum = " + sum); } }
Sum = 25
Knowing how for-each or enhanced for loop in Java works, it is time to weigh it against the regular for loop. Let’s code an example to understand the difference better.
class Main { public static void main(String[] args) { char[] alphabets = {'a', 'b', 'c', 'd', 'e'}; // iterating through an array using a for loop for (int i = 0; i < alphabets.length; ++ i) { System.out.println(alphabets[i]); } } }
a b c d e
Looks rather complex… right? Let’s now run the same code using for-each or Java enhanced for loop.
class Main { public static void main(String[] args) { char[] alphabets = {'a', 'b', 'c', 'd', 'e'}; // iterating through an array using the for-each loop for (char item: alphabets) { System.out.println(item); } } }
In the examples above, it is clear how for-each simplifies loop deployment while ensuring the result remains unchanged.
The for-each or Java enhanced for loop helps us seamlessly iterate elements of a collection or an array and massively cuts the workload. Subsequently, it helps write and deploy codes faster and simplifies app development in Java.
Despite this, for-each is not a universal replacement for regular for loop, and you must not break ties with the original. The former only works for simple tasks, while the latter offers more control over iterations and liberty to track what happens index by index.
That said, if you don’t want to track indexes and are only concerned about the output, then it is best to turn to for-each or enhanced for loop in Java. So, now you understand how the Java enhanced for loops work and what they can and cannot do.
Also Read: JShell: A Comprehensive Guide to the Java REPL (Read Evaluate Print Loop)
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use