Learn Java Easy. Chapter 16. Final Preparations / For-each Loops

Chapter 16. Final Preparations / For-Each Loops

Chapter 16. Final Preparations / For-Each Loops

There’s nothing left to do; we’re escaping next Monday. Today is Tuesday, so we have enough time to prepare everything. Tomorrow, Chani’s cousin will come, and I’ll give him all the information. On the other hand, I need to explain exactly where we’ll meet. I also need to tell Phil, as he will be the one to pick me up and bring me back to prison without anyone noticing.

I’ve had plenty of time to choose the location, and I’m sure it’s the perfect place. Once we escape, we’ll go to a house owned by a friend of Pedro’s. That’s where we’ll separate, as each of us has our own plan. Near that house, there’s a small public library that almost nobody uses. It’s possible to reserve rooms, so Chani can even hide some microphones in advance to record the conversation.

There’s a small parking lot nearby where there are always free spaces. That’s where I’ll meet Phil. It’s located in a somewhat marginal neighborhood, so it’s very unlikely there are cameras. Still, nobody will be looking for me since everyone will assume I’m still in prison. Nevertheless, I like to be cautious, something I’ve learned from Bud and Pedro.

It’s important that my voice doesn’t appear in the recording that incriminates Rich. Otherwise, the authorities would find out that I left prison, and I’d be in trouble. Chani could remove the parts where I appear, but an edited audio would lose credibility. Therefore, once I enter the library room, I must remain silent. To avoid it seeming strange, it’s vital that I greet Rich outside the library. I’ll be able to have a completely natural conversation, and then, once inside the room, let them two talk.

I have everything well planned, but I hope there aren’t too many unexpected events. The truth is, I’m worried about not being able to control what happens outside the prison. It’s easier here, and besides, I have help. Outside, I’ll be alone; I’ll count on Chani’s and Phil’s support, but it’s not the same. I don’t trust them as much as I do my fellow prisoners.

Tonight I’ll continue with my Java classes. I’m sure I’ll get a good grade on my next university exam. It seems we’re going to cover a type of loop that we didn’t see when we addressed the topic earlier. The truth is, I quite liked the loop exercises, so I imagine this topic will also be entertaining and easy to understand.

Advantages of for-each loops

Some topics ago, we covered the concept of loops and worked in depth on for and while loops. Now we’re going to focus on another type that I deliberately left aside at the time. Even focusing on just two types is a somewhat dense concept and a complicated topic. But your programming level is much higher now, so you can handle this and more.

For-each loops are a fundamental tool due to their simplicity and efficiency when iterating over collections and arrays. The main advantages of using this type of loop are as follows:

  • Simplicity and better readability: The syntax is clearer and more concise than that of traditional loops (for or while). This makes the code easier to understand.
  • Error reduction: By eliminating the need to manually handle indices, the risk of errors such as index overflow (accessing a position outside the array range) is reduced.
  • Convenience: It’s especially useful for iterating over collections of objects, such as lists and sets, where indices are not as relevant.

But it’s not all advantages; otherwise, we would only use this type of loop, so let’s look at the disadvantages and those situations where it’s better not to use them.

  • Limitation when working with indices. You cannot directly access the index of the current element. If you need the index, you must use a traditional for loop.
  • Cannot modify the collection: If you need to add or remove elements from the collection while iterating, a for-each loop is not suitable.
  • Only forward iteration: The for-each loop only allows forward iteration, so you cannot traverse the collection in reverse.
  • Limitations in multidimensional arrays: This is basically because in these cases it’s somewhat more complicated and less intuitive to use for-each compared to traditional loops.

Syntax of the for-each loop

The basic syntax of the for-each loop in Java is as follows:

for (ElementType temporaryVariable : array) {

       // Code that uses temporaryVariable

}

The syntax is simple: first we see the data type and then the temporary variable. Basically, this will take a different value each time the loop makes an iteration. Finally, we put the array that will be traversed. Let’s see it with a real data example:

public class Main {

     public static void main(String[] args) { 

              int[] numbers = {1, 2, 3, 4, 5};

                   for (int number : numbers) { 
                   System.out.println(number);

               }

       }

}

In this example:

  • int is the type of elements in the “numbers” array.
  • “number” is the temporary variable that takes the value of each element in “numbers”.
  • “numbers” is the array being iterated.

Now let’s see an example with a text array:

public class Main {

      public static void main(String[] args) {

               String[] fruits = {"Apple", "Orange", "Banana"};

               for (String fruit : fruits) { 
  
                       System.out.println(fruit);

                }

       }

}

In this example:

  • String is the type of elements in the fruits array.
  • fruit is the temporary variable that takes the value of each element in fruits.
  • fruits is the array being iterated.

Since this topic has been very short and a continuation of the loops topic, we’re not going to make a summary of it. Doing so would simply be repeating the same thing again. As you’ve been able to observe, the syntax is very simple. Although for it to be engraved in your mind and for you to gain confidence, I recommend that you do all the exercises I propose below.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏