Understanding the ForEach (Enhanced For Loop) in Java

May 05, 2023
Understanding the ForEach Enhanced for loop in Java



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).

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.

new Java jobs

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.

What Does Java Enhanced For Loop Do?

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.

Java Enhanced for Loop Syntax

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.

Enhanced for Loop in Java Example

class ForEachExample {

public static void main(String[ ] args)  {

int [ ] odd numbers = { 1, 3, 5, 7 };

for( int number : odd numbers) {

System .out.println(number);

      }

    }

}

Output:

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.

Multiplying Array Elements using Enhanced for Loop in Java

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);

        }

  }

}

Output:

3

9

15

21

Summing Array Elements using Java Enhanced for Loop

// 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);

 }

}

Output:

Sum = 25

For Loop vs For-Each Loop: Which One Is Better?

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.

1) Using for Loop

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]);

   }

 }

}

Output:

a

b

c

d

e

Looks rather complex… right? Let’s now run the same code using for-each or Java enhanced for loop.

2) Using for-each 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);

   }

 }

}

Output:

a

b

c

d

e

In the examples above, it is clear how for-each simplifies loop deployment while ensuring the result remains unchanged.

The Final Word

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)

new java job roles



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US