© Monstar Studio / Shutterstock.com

Today we are reviewing Java’s For-Each Loop, an extension of the classic For loop. These loops were added to Java5 in 2004 and nowadays are an essential tool when working with arrays and collections.

The plan is to teach you the fundamentals, which entail understanding the logic behind For-Each loops and also their syntax. This is a tool you can use in almost any project to give your programs a powerful boost in functionality and efficiency.

What are For-Each Loops?

The For-Each loop’s primary function is to deal with arrays. The idea is that this loop gives you the power to iterate through the items of an array or collection. 

Each item is ready for modifications inside the functionality of the loop body. Then, the return will be a new array. You can apply any logic inside the For-Each loop. This means the return on investment for this tool is off the charts: you can apply it to basically any array you can think of.

Imagine you’re working with a list of names, emails, locations, or any lengthy database. Now, imagine that you can prepare it for further operations with one simple command. Exactly. 

Now, let’s see how to build and apply For-Each loops.

Code Examples

The syntax of For-Each loops is clear and easy to understand if you are familiar with Java.

for (type var : array)
     statements using var;

We start with the keyword For followed by the declaration of the array we want to iterate. Then, we declare any logic we want to apply (between the curly braces).

Now let’s write a program using these concepts.

class First
     public static void main(String[] args)
          int array[] = {1,2,3,4,5};
          for (int element : array)
               System.out.print(element + " ");

//1 2 3 4 5 

In the above example, we first established an array with some items so we can process them. After that, we declared the actual For-Each loop. 

It’s vital to declare the type of array to which we’re applying the For-Each loop, as this usually avoids errors and bugs.

Finally, the loop will return each item in every iteration, as seen in the output section. 

All programmers like efficiency. Well, one of the advantages of For-Each loops is that they avoid the extra steps necessary for declaring the logic of a normal For loop. Let’s see this in an actual example:

//For loop syntax

for (int i=0; i

Both methods give us the same result, but the For-Each Loop is a clear winner. The logic is much cleaner and easy to understand, making its functionalities more accessible to new programmers. 

However, even if For-Each loops look cleaner, there are some things they can’t do. Let’s talk about this in-depth.

Disadvantages of For-Each Loops

The first problem with For-Each loops is that they cannot modify the original array. This isn’t a problem when working with dynamic programs that must save the initial state. But there might be situations when a classic For Loop would be a better choice. Let’s see this in code:

for (int : marks)
     num = num*2;

// the original array stays the same

Unluckily, For-Each loops can’t keep track of the index within an array. Therefore, we can’t use any logic that implies obtaining the index of an element.

for (int num : numbers)
     if (num == target)
          return ???;   // index can't be found

For-Each loops cannot iterate backward through an array. Also, nesting loops and booleans are other areas where a For-Each Loop might not be a good idea.

Why Use For-Each Loops?

As its name suggests, this loop checks out every item of a collection or array. This allows us to process large databases with ease and efficiency.

The iteration of data is an everyday task for programmers, so any tool we can add to our skillset that will help with it should be welcomed with open arms.

With For-Each loops, the advantages of a cleaner and easy-to-understand code are worth the lack of some features, such as array modification. You can always use the classic For Loop if you need this particular functionality. So don’t worry if you can’t always apply the easier-to-write code, but keep it in mind for situations when it could save you hours of work!

Let’s explore other functionalities of the For-Each loop. This will give you a hint of what it can do in combination with other tools.

Let’s say we have a collection of arrays with data in them. Our goal will be to flatten this data into a single array with the For-Each loop. Check this out:

// stream of arrays

Input: arr[][] = {{1,2,3},{4,5,6},{7,8,9}}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

As you can see in the code, we have a stream of arrays ready for processing. Each array contains a series of numbers. The code we’ll write will include some other Java methods, so take this as an opportunity to test your understanding of this coding language!

Let’s see how each code segment works.

class exmpl

    // Main function
    public static  Stream flattenStream(T[][] arrays) 
         List list = new ArrayList<>();

         for (T[] array : arrays)
          return list.stream();

    public static void main(String[] args)
          Integer [][] arr={
          Integer[] flatArray = flattenStream(arr)
                    .toArray(Integer[] ::new);

First, we established a function that contains everything else and declared a list to collect the items.

The next step is using the For-Each loop combined with the stream() method. Given the list of numbers, each item is now a stream of the list. The final return, outside of the For-Each loop, is the list converted into a single stream of information. 

When the stream is ready, it’s time to flatten the array. We declare each number, and then we call the function we previously coded onto each one. This function takes the data and returns everything in a single array.

This is just a minuscule example of how these fundamental tools allow you to handle data as a programmer. With them, you can play with information and find new ways to make your code more efficient and easier to debug.

Conclusion: How To Use For-Each Loop In Java

For-Each loops are the easiest way to iterate through an array or collection. The items collected in the chosen array get processed with any functionality we desire. Also, this processing can be done using a combination of multiple methods and functions.

Remember, these loops lack some features. Chiefly, they don’t support backward iteration, loop nesting, and index tracking. Always use a classic For Loop to avoid bugs if you need any of those functionalities. 

Nevertheless, the possibilities for development are limitless when you combine the For-Each Loop with other methods, such as stream(). This is what we want to leave you with. Always look for new ways to expand your horizon as a programmer, and never settle for a single toolset. 

We recommend taking a look at Java’s official documentation for further information.

How To Use For-Each Loop In Java FAQs (Frequently Asked Questions) 

When was Java developed?

Java was released in May 1995 and developed by James Gosling at Sun Microsystem. It is one of the most popular object-oriented programming languages, with 9 million regular daily users.

How do I install Java?

To install Java, you need to visit the download section on Java’s website and then choose the correct installer for your system. It’s free! Java is available for Windows, Mac, Linux, and Solaris.

What is a classic For loop?

A For loop is a method for iteration built with a condition and a body. It allows the user to run a code section repeatedly until the condition is reached. A For loop is an alternative for While loops, used when the number of iterations needed is fixed.

How does the Java For-Each loop work?

For-Each loops work very similar to a classic For loop. When used, the return is the same with either statement, but with For-Each loops, the syntax is much more accessible.

Can I use For-Each loops with index-based functions?

Sadly, no. For-Each loop can’t keep track of index position in an array. Luckily, the classic For loop allows you to use this logic without errors.

About the Author

More from History-Computer

  • W3Schools Available here: https://www.w3schools.com/java/java_foreach_loop.asp
  • Programiz (1970) https://www.programiz.com/java-programming/enhanced-for-loop
  • GeeksForGeeks Available here: https://www.geeksforgeeks.org/for-each-loop-in-java/
  • GeeksForGeeks Available here: https://www.geeksforgeeks.org/flatten-a-stream-of-arrays-in-java-using-foreach-loop/?ref=rp\
  • Baeldung Available here: https://www.baeldung.com/java-for-each-loop