Learn Java Easy. Chapter 5. Meeting Bud. Learning to use loops

Chapter 5: Meeting Bud and Learning Loops in Java

Chapter 5. Meeting Bud. Learning to use loops

I can’t stop thinking about how quickly life can change. Fernando and Rich have been quite lucky, but I haven’t been so fortunate. It seems that the police have found something on my computer, although they haven’t specified anything yet. My lawyer says I’m facing several years in prison, but I don’t even know what I’m being accused of.

While I wait for my trial, my new home is a small shared cell. The bed is very uncomfortable, everything smells terrible, and worst of all, there’s no privacy when using the bathroom. It’s going to be difficult to get used to. In real life, your head is full of stimuli everywhere. It stays busy, you think little and don’t get bored. Here there’s absolutely nothing to entertain yourself with. I miss my phone a lot. I can barely communicate with my friends and family, only with the closest ones. I’d like to tell everyone that I’m innocent and that I haven’t done anything wrong. I don’t know what people think of me, but I’m sure it’s nothing good.

When you have too much free time, you keep thinking about things. Obviously, I think about what happened. You don’t have to be very smart to realize that the culprit is Chani. He mysteriously disappeared a few days before the police showed up. During the party, our computers were inside his cabinet and therefore he could have accessed any of them. Moreover, it’s very strange that no one can locate him anywhere and that his phone is disconnected.

I wonder why he would do it. I mean, why blame me or Rich? We were friends. We always had a good time and never had any kind of problem. I imagine he needed someone to blame and, in the end, it fell on me. I’d like to know where he is and if he made any money from his crime. I want to understand why he did it and what kind of trouble he’s in. I’m aware that I might never know, but I still have the feeling that someday I will.

It’s obvious that I’m quite worried since I don’t know how long I’ll have to be here. Every minute is torture and I wouldn’t like to have to spend much more time here. Deep down, I trust that everything will be clarified. I have nothing to hide and, moreover, I have Rich’s favorable testimony. He will be able to help me prove that Chani is the real culprit.

My family has managed to get a good lawyer, he’s preparing the case and will soon inform me of what strategy to follow and what sentence I might face. In general, I feel quite supported and that allows me to move forward. Visits brighten my days and break the monotony. Although it affects me to see their worried faces, it comforts me to know that I have people behind me fighting from the outside. I wouldn’t want to be completely alone. In here I’m defenseless and it’s impossible for me to get evidence of my innocence. Now I can only trust that other people will get me out of this situation.

Now that you know my mood is good, you might wonder what prison life is like. I’m not just referring to what it feels like to be inside the cell; I’ve already explained that. I’m talking about the relationship with other inmates, the food, the yard, physical security…

I’m not going to lie. The first day I was very scared. From the moment I entered prison, I felt a very strange sensation in my body. I could barely breathe. I felt a strong pressure in my chest that practically didn’t allow me to speak. In movies they always say you have to pretend to be tough, but I couldn’t fake it. I just walked looking at the ground until I reached my cell.

Luckily, that feeling didn’t last long. Specifically, it faded when I met my cellmate, a man from Valencia called “Bud”. Well, I think it’s obvious that’s not his real name. He introduced himself that way and I never asked anything more.

Bud has been in the same cell for the last 8 years and is very respected by everyone there. He knows many people, both inmates and prison officials. So being his friend can offer me practically total immunity. As long as I don’t look for trouble, people will leave me alone.

Quickly, Bud became interested in my story. He wanted to know how I had gotten there. I explained the situation and he was understanding. Later, he informed me that he was there because he tried to rob a jewelry store. He didn’t want to give more details and never would.

We continued chatting and I ended up telling him that I was studying computer engineering. He asked if I knew how to program in Java and I told him I had some notions. Then, he explained that to reduce his sentence, he helps prison officials with security software. That allows him to have a laptop from time to time.

I thought he was very lucky. My stay in the cell would be much more pleasant if I could have a computer and internet access. Besides being able to contact my relatives and friends, I could even learn Java. Being friends with the guards can have great advantages.

I think Bud read my mind because, quickly, he told me he could help me improve my programming skills. After giving me a small improvised test, he was able to roughly calculate my level. He asked if I knew what loops were. The truth is I had no idea, so I told him no.

That’s how I got a private Java teacher in prison. I felt very fortunate about it and didn’t want to disappoint my new mentor. So I took it very seriously. The loop lesson had begun and next I’m going to tell you everything Bud explained to me.

Loops

Definition, purpose and importance of loops in programming

A loop in programming is a way to make your program repeatedly execute a block of code while a certain condition is met. Loops are a fundamental tool not only in Java, but in any programming language. This is because they allow us to automate repetitive tasks efficiently.

In Java, there are mainly three types of loops: for, while, and do-while. Each of these loops has its own syntax and specific application, but they all share the same essential purpose: to repeatedly execute a set of instructions.

I’ll explain the three types of loops, but I advise you to focus only on the first two, for and while. I consider that if you’re taking your first steps in Java, it’s fundamental to master a few basic things instead of trying to cover everything. However, it’s important that you’re aware that there are three. If you really like programming and it becomes part of your life, at some point you’ll encounter do-while loops and I don’t want to catch you by surprise.

Introduction to loops

For loop: It’s used when the number of iterations to be performed is known in advance.

While loop: It’s used when you’re not sure how many times a block of code should be repeated and the termination condition depends on some variable that is evaluated in each iteration.

Do-while loop: Similar to while, but guarantees that the block of code executes at least once, since the condition is evaluated after the first execution.

After reading this small definition, you most likely still don’t know what we’re talking about, although you’re getting an idea. Nevertheless, don’t worry because when we see practical examples, everything will become clear. However, before that, it’s necessary to list the main reasons for the importance of loops.

  • Automation of Repetitive Tasks: Loops allow us to automatically execute repetitive tasks; this way, we don’t need to write the same code several times. This will be especially useful for operations such as processing list elements, reading files, or generating number sequences.
  • Efficiency and Performance: If we use loops appropriately, we can significantly improve the efficiency and performance of our programs. We’ll avoid redundancy and thus reduce the amount of code needed to perform repetitive tasks. This will optimize system resource usage.
  • Facilitates Code Maintenance: Code that uses loops is generally easier to understand, maintain and modify. If the logic of a repetitive operation needs to be changed, only the code block inside the loop needs to be modified instead of changing multiple instances of the same code.
  • Handling Collections and Data: Loops are particularly useful for handling data collections, such as arrays and lists. They allow you to traverse the elements of these collections and perform operations on each of them systematically.

For Loop

A for loop in Java is a way to repeat a block of code a specific number of times. It’s useful when we know how many times we want the code to execute.

A for loop has three main parts:

  • Initialization: Sets up a variable to start.
    • Condition: While this condition is true, the loop will continue executing.
    • Update: Changes the variable after each loop repetition.

Here’s the basic structure of a for loop:

for (initialization; condition; update) {

      // Code to repeat

}

Example 1: Display numbers from 1 to 5.

for (int i = 1; i <= 5; i++) {

     System.out.println(i);

}

Let’s analyze this exercise carefully. The first thing we need to do is declare a variable. As you can see in the example, we’ve given it the name “i”. It would work the same regardless of the name, but you’ll always see it written this way. Therefore, I recommend you do the same.

The second thing we see is that the variable i must be less than or equal to five. Finally, i++ means that after each repetition, i is incremented by 1.

If we had wanted to do a countdown, showing the numbers from 5 to 1, we would do it as follows:

for (int i = 5; i >= 0; i--) {

     System.out.println(i);

}

Again we start by declaring the variable “i” and also assign it the value of the first data we need, in this case, 5. Then we say that the values we want to show must be equal to or greater than 0. Finally, we use i– so that i decreases one by one.

Loops aren’t just for displaying lists of numbers. Little by little you’ll see they can be used for many things. Let’s see another example:

We create a program that displays “Hello” three times in a row:

for (int i = 0; i < 3; i++) {

      System.out.println("Hello");

}

We need a loop that repeats exactly three times. Perfect, since we know exactly the number of times, we use a for. We follow the same structure as before; in this case, we say that i starts at 0 and we need i to repeat three times, so:

The first i will be = 0 The second i will be = 1 The third i will be = 2

Therefore, we need the condition to be that i is less than or equal to 2. We could have done it in two ways and it would be exactly the same:

– i < 3

– i <=2

In this case, we don’t care much whether our variable starts at 0, 1 or any other number, for example, 33. We simply need the loop to repeat three times. It could have been like this:

for (int i = 33; i <=35; i++) {

     System.out.println("Hello");

}

Since we already have a loop that repeats three times, we simply use one line of code to print each time.

Things are going to get a bit more complicated when we see the exercises, but I hope you’re understanding the basics. The for loop is usually quite easy to learn, since you just have to follow specific steps. You create a variable with the first value, define the second and then end with i++ or i–, depending on each scenario. The while loop, on the other hand, isn’t as structured and, although it may initially seem even simpler than the for, when you face complex exercises is when you realize that applying the while isn’t as intuitive as you thought. Nevertheless, you’ll see how you learn it without problems right away.

While Loop

A while loop follows this basic structure:

while (condition) {

      // Code to repeat

}

It seems very simple, right? Well, the truth is it is. Maybe I put a little fear in you before saying it’s more difficult than the for loop. Actually, when we explain basic exercises, everything seems very simple, but afterwards, when the statements get more complicated, that’s when you’ll have to think things through to find the answer you’re looking for. But let’s not get ahead of ourselves, let’s see an example:

We’re going to use a while loop to print the numbers from 1 to 5.

int i = 1; // Initialization while (i <= 5) {

        // Condition

        System.out.println(i); i++; // Update

}

We create and assign a value to an int variable outside our loop. For now, and before starting the loop, the variable still has a value of 1. But variables can change value as the program progresses. Remember that when executed, the program reads the lines of code from top to bottom.

When the loop is executed for the first time, i is one, and it will display the System.out.println(i); line of code; in this case “1”.

But what happens right after? We find an i++, so now i is 2. Since we said the loop doesn’t close until i is equal to or greater than 6, it will display System.out.println(i); again and in this case we’ll see “2”.

What happens in the next iteration? i is 3… the cycle repeats again. This continues until reaching 6, and at that moment the loop closes and it won’t display it.

Let’s level up a bit?

I’ll use an exercise similar to the previous one, since it will be familiar to you. In this case, we’ll create a loop from 1 to 10. But we’re going to put an if inside. We’ll display a text that says: “The value is greater than 6”. We need i to be displayed and then, next to it, the text I mentioned, for i = 7, 8, 9 and 10.

public class Main {

    public static void main(String[] args) {

          int i = 1;

          while (i <= 10) {

               if (i<=6) {

                     System.out.println(i);

                } else System.out.println(i + " The value is greater than 6"); i++;

            }

    }

}

It’s simple. Once we had the loop done, we needed one thing to happen for the first 6 numbers and something different for the next 4. The first six only show the value of i, while the next 4 show i and also the message. You can try repeating the exercise on your own using a for loop instead of the while I used. It’s even easier.

Do While Loops

A do-while loop is a structure that repeats our instructions while a condition is met. What differentiates it from other loops is that it always executes the code at least once, even if the condition is false from the beginning.

  • First, the code inside the loop executes.
  • Then, the condition is evaluated.
  • If the condition is true, the code executes again. If it’s false, the loop ends.

This type of loop is useful when we want to ensure that the code block executes at least once, regardless of the condition. Here’s an example:

int number = 1;

do {

System.out.println(number);  // Prints the current number

number++;  // Increments the number by 1

} while (number <= 5);  // Repeats while the number is less than or equal to 5
  • First, it prints the number 1.
  • Then it checks the condition number <= 5. Since it’s still true, the loop continues.
  • The process repeats until the number reaches 6, at which point the condition becomes false and the loop ends.

Break Concept

When the program encounters a break, it exits the loop and continues with the next line of code outside the loop. The use of break is important for two main reasons.

  • The first is that it allows us to exit a break prematurely. Something you’ll see is necessary to do in many situations. Not to mention, in several of the exercises at the end of the chapter.
  • The second is that it improves program efficiency by saving resources. If you know you’ve already found what you were looking for, there’s no need to go through the loop to the end.

Moreover, break will help us simplify program logic; it makes the code cleaner, simpler and easier to understand. Finally, it will be an elegant solution for handling exceptional cases. In some cases, within a loop you can encounter exceptional situations such as errors or invalid conditions that require closing the loop immediately. You won’t find anything simpler or faster than a break.

Break Usage Example

Imagine you create an infinite loop using a while loop. We could do it as follows:

int a = 1;

       while (a >= 0) { a++;

       if (a > 10) {

       System.out.println(a);

       }

}

According to that loop, while a is greater than 0, it will keep repeating. Our program would infinitely display number after number one by one on our screen. However, we want it to display only the number after 10 and then close the loop.

int a = 1;

while (a >= 0) { a++;

      if (a > 10) {

      System.out.println("First number greater than 10 is = " + a);

      break; // Exits the loop when the first number greater than 10 is found

      }

}

By this point you’ve probably realized that this exercise could have been done another way. Not only that, but it can be done in many different ways. Code is just a tool that programmers have to solve problems. It’s at our disposal and can be used as best suits us in each situation.

Continue Concept

A continue is used to jump to the next iteration of the loop, skipping the code in between inside the loop for the current iteration. When our program encounters a continue instruction, the loop doesn’t stop, but jumps to the next iteration. This is useful when you want to skip certain iterations under specific conditions without stopping the loop completely.

Continue Example

Imagine you have a loop that counts from 1 to 10, but you want to skip the number 5. You can use continue to achieve this.

public class Main {
     public static void main(String[] args) {

     for (int i = 1; i <= 10; i++) {

     if (i == 5) {

     continue; // Skips the rest of the loop when i equals 5

     }

     System.out.println(i);

     }

   }

}

Both concepts, break and continue, are useful tools for controlling execution flow within loops in Java, allowing you to manipulate iteration according to your specific needs.

String Manipulation

Although string manipulation could perfectly have its own topic, to not extend things too much I’ve decided to show you how this concept works in this chapter. Moreover, from now on you’ll see two specific methods in the exercises and, so you’re not caught by surprise, I’m going to explain what they are and what they’re used for. This will greatly enrich your knowledge of syntax.

charAt() and length() Methods

– The charAt() method

The charAt() method in Java is used to get the character at a specific position within a text string. It takes an index as an argument and returns the character at that position within the string.

Syntax:

char charAt(int index)

index: It’s the index of the character you want to get. The first character of the string has an index of 0, the second has an index of 1, and so on.

Example:

String text = "Hello World"; char character = text.charAt(0);

System.out.println("The character at position 0 is: " + character); // Output: 'H'

In this case, charAt(0) returns the first character of the string “Hello World”, which is ‘H’. If you use another index, you’ll get the character at that position, for example charAt(5) would return ‘M’.

– The length() method

The length() method in Java is used to find out how many characters a text string has. It returns an integer that represents the length of the string.

Syntax:

int length()

Example:

String greeting = "Hello";

int length = greeting.length();

System.out.println("The length of the string is: " + length); // Output: 4

It’s not very complicated; in the following exercises you’ll encounter these methods several times. As soon as you start working with them, you’ll see they’re very easy to use.

Summary of what we learned

A loop allows a block of code to execute repeatedly while a specific condition is met. This technique is essential to efficiently automate repetitive tasks. In Java, the main types of loops are for, while and do-while, each with a particular structure and use.

The for loop is used when the number of times the code should execute is known in advance. On the other hand, the while loop is used when you don’t know how many times the block of code will repeat, since the termination condition depends on a variable evaluated in each iteration. The do-while loop, on the other hand, is similar to while, but guarantees that the block of code executes at least once, evaluating the condition after the first execution.

Loops are necessary for several reasons:

  • They automate repetitive tasks, allowing code to execute multiple times without needing to write it repeatedly.
  • They improve efficiency and performance by reducing redundancy and optimizing resource usage. Moreover, they facilitate code maintenance, since it’s simpler to modify a code block inside a loop than multiple instances of the same code.
  • They’re especially useful for handling data collections, such as arrays and lists, allowing systematic operations to be performed on each element.

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