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 the police 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 await 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 to use the bathroom. It’s going to be difficult to get used to. In real life, your head is full of stimuli from everywhere. It stays busy, you think little, and you don’t get bored. Here there’s absolutely nothing to entertain yourself with. I really miss my phone. 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 will think of me, but surely nothing good.

When you have too much free time, you can’t stop thinking about things. Obviously, I think about what happened. You don’t have to be very smart to realize that Chani is the guilty one. 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. Besides, it’s very strange that nobody can locate him anywhere and that his phone is disconnected.
I wonder why he would do it. I mean, why frame me or Rich? We were friends. We always had a good time and never had any kind of problem. I guess 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 involved in. I’m aware that I might never know, but still, I have the feeling that someday I will.
It’s obvious that I’m quite worried, as 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 cleared up. I have nothing to hide and, additionally, I have Rich’s favorable testimony. He can help me prove that Chani is the real culprit.

My family has gotten a good lawyer, who is preparing the case and will soon inform me of the strategy to follow and what sentence I could face. Overall, I feel quite supported and that allows me to keep going.
The visits brighten my days and break the monotony. Although it affects me to see their worried faces, it’s comforting 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 all I can do is trust that other people will get me out of this situation.
Now that you know my mood is good, perhaps you’re wondering what life in prison is like. I don’t just mean how it feels to be inside the cell; I’ve already explained that. I’m talking about relationships 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 barely allowed me to speak. In movies they always say you have to pretend to be tough, but I couldn’t pretend. I just walked looking at the ground until I reached my cell.
Fortunately, that feeling didn’t last long. Specifically, it vanished 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 highly respected by everyone there. He knows many people, both inmates and prison officers. 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 ended up 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 would never give them to me.

We continued chatting and I ended up mentioning that I was studying computer engineering. He asked if I knew how to program in Java and I told him I had some knowledge. Then, he explained that, to reduce his sentence, he helps the prison officers with security software. This allows him to have a laptop from time to time.
I thought I 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 family and friends, I could even learn Java. Being friends with the prison guards can have great advantages.

I think Bud read my mind because he quickly told me that he could help me improve my programming skills. After giving me a small improvised test, he could more or less calculate my level. He asked me 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 tutor in prison. I felt very lucky for it and didn’t want to disappoint my new mentor. So I took it very seriously. The lesson on loops had begun and I’m going to tell you everything that 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 will explain the three types of loops, but I advise you to focus only on the first two, for and while. I believe that if you’re taking your first steps in Java, at first it’s essential 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 come across do-while loops and I don’t want them to catch you by surprise.
Introduction to loops
- for: Used when you know in advance the number of iterations that need to be performed.
- while: Used when you don’t know for certain 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: Similar to while, but guarantees that the code block is executed at least once, since the condition is evaluated after the first execution.
After reading this brief definition, you probably still don’t fully understand what we’re talking about, although you’re getting an idea. Don’t worry though, because when we look at practical examples, everything will become clear. However, before that, it’s necessary to list the main reasons why loops are important.
Automation of Repetitive Tasks: Loops allow us to automatically execute repetitive tasks; this way, we don’t need to write the sa same code multiple times. This will be especially useful for operations like 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 the use of system resources.
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, you only need to modify the code block within the loop 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.
Loop for
UA 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 named it “i”. It would work the same regardless of the name, but you’ll always see it written like this. 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.
Lastly, i++ means that after each repetition, i increases by 1.
If we had wanted to do a countdown, to show 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, additionally, we assign it the value of the first data we need, in this case, a 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 showing lists of numbers. Little by little you’ll see that they can be used for many things. Let’s look at another example:
Let’s create a program that shows “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 care little 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");
}
Now that we have a loop that repeats three times, we simply use a line of code to print each time.
Things will get a bit more complicated when we look at the exercises, but I hope you’re understanding the basics. The for loop is usually quite simple 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, is not so structured and, although at first it might seem even simpler than the for loop, when you face complex exercises is when you realize that applying while is not as intuitive as you thought. Even so, you’ll see how you’ll learn it quickly without problems.
Loop While
A while loop follows this basic structure:
while (condition) {
// Code to repeat
}
Seems very simple, right? Well, the truth is that it is. Maybe I scared you a bit before by telling you it’s more difficult than the for loop. Actually, when we explain the basic exercises, everything seems very simple, but later, when the statements become 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 look at an example:
Let’s use a while loop to print 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 type 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 executing, the program reads the lines of code from top to bottom.
When the loop executes for the first time, i equals one, and it will show the line of code System.out.println(i); in this case “1”.
But what happens right after? We find an i++, so now i equals 2. Since we said the loop doesn’t close until i is equal to or greater than 6, it will show System.out.println(i); again and in this case we’ll see “2”.
What happens in the next iteration? i equals 3… the cycle repeats again. This continues until reaching 6, and at that moment the loop closes and won’t show it.
Shall we raise the level a bit?
I’ll use an exercise similar to the previous one, as 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 show a text that says: “The value is greater than 6”. We need it to show i 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 to repeat 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 makes it different 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 is executed.
- Then, the condition is evaluated.
- If the condition is true, the code is executed again. If it’s false, the loop ends.
This type of loop is useful when we want to make sure the code block is executed at least once, regardless of the condition. Here’s an example:
int number = 1;
do {
System.out.println(number); // Prints the current number
number++; // Increases 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 verifies 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
Cuando el programa encuentra un break, sale del bucle y continúa con la siguiente línea de código ya fuera del bucle. La utilización del break es importante sobre todo por dos motivos.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 mainly for two reasons.
- The first is that it allows us to exit a break prematurely. Something that you’ll see will be necessary to do in many situations. Without looking too far, in several of the exercises at the end of the topic.
- 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 until the end.
Furthermore, break will help us simplify the program’s 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 might encounter exceptional situations such as errors or invalid conditions that require immediately closing the loop. You won’t find anything simpler or faster than a break.
Example of using break
Imagine that you create an infinite loop using a while loop. We could do it in the following way:
int a = 1;
while (a >= 0) {
a++;
if (a > 10) {
System.out.println(a);
}
}
According to that loop, as long as a is greater than 0, it will keep repeating. Our program would be infinitely showing number after number, one by one on our screen. However, we want it to show only the number after 10 and then for the loop to close.
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 now you will have realized that this exercise could have been done in another way. Not only that, but it can be done in many different ways. The code is just a tool that the programmer has to solve problems. It’s at our disposal and can be used as best suits us in each situation.
Concept of continue
A continue is used to skip to the next iteration of the loop, omitting the code in between within the loop for the current iteration. When our program encounters a continue instruction, the loop doesn’t stop, but instead jumps to the next iteration. This is useful when you want to skip certain iterations under specific conditions without stopping the loop completely.
Example of continue
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 is equal to 5
}
System.out.println(i);
}
}
}
Both concepts, break and continue, are useful tools for controlling the execution flow within loops in Java, allowing you to manipulate the iteration according to your specific needs.
String Manipulation
Although string manipulation could perfectly well have its own topic, to avoid making things excessively long I’ve decided to show you how this concept works in this topic. Additionally, from now on you’ll see two specific methods in the exercises and, so they don’t catch you by surprise, I’m going to explain what they are and what they’re used for. This will notably enrich your knowledge of the 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: Is the index of the character you want to obtain. 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 ‘W’.
- The length() Method
The length() method in Java is used to know 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 complicated at all; in the following exercises you’ll encounter these methods several times. As soon as you start working with them, you’ll see that they are very simple to use.’
Summary of what you’ve learned
A loop allows a block of code to be executed repeatedly while a specific condition is met. This technique is essential for efficiently automating repetitive tasks. In Java, the main types of loops are for, while, and do-while, each with its particular structure and use.
The for loop is used when the number of times the code should be executed is known in advance. In contrast, the while loop is used when it’s not known how many times the code block will be repeated, as the termination condition depends on a variable evaluated in each iteration. Meanwhile, the do-while loop is similar to while, but guarantees that the code block is executed at least once, evaluating the condition after the first execution.
Loops are necessary for several reasons:
- First, they automate repetitive tasks, allowing code to be executed multiple times without having to write it repeatedly.
- Second, they improve efficiency and performance by reducing redundancy and optimizing resource use. They also facilitate code maintenance, as it’s easier to modify a block of code within a loop than multiple instances of the same code.
- Finally, they are especially useful for handling data collections, such as arrays and lists, allowing systematic operations on each element.
Additionally, in this topic we’ve seen two very useful commands when working with conditionals.
- The concept of “break” is used to exit a loop before completing all iterations. This is useful for improving Program efficiency and simplifying code logic, making it cleaner and easier to understand.
- On the other hand, “continue” is used to skip to the next loop iteration, omitting the intermediate code for the current iteration. Both concepts are valuable tools for controlling execution flow within loops in Java and manipulating iteration according to the Program’s specific needs.