Chapter 4. Hanging Out at the Police Station / Working with Conditionals
I don’t know how it happened, but I am at the police station. Specifically, locked in a room with Rich and his friend, who, by the way, is named Fernando. The story is quite simple to tell, although it makes no sense to me. I don’t know exactly what is happening or why I have been detained.
Shortly after Fernando arrived home, the police burst in without warning. Everything happened very fast. Several armed men entered shouting and ordering us to lie on the floor. They gathered the three of us in the living room and made us sit on the floor. Meanwhile, they started searching the entire house. I don’t know what they were looking for, but it was clear they didn’t want to leave anything behind. The search seemed very thorough.

A few minutes after the search started, I saw a policeman leaving with our computers. I couldn’t help but think that they had been able to open Chani’s closet, while we had been unable to access our things for two days. It didn’t seem fair. I also wondered who was going to clean up that mess. We had just cleaned the whole house and now everything was even worse than after the party. But what crossed my mind the most was the bad luck Fernando had. He had never come before and, 20 minutes after arriving, the police show up. At no point have I thought that his visit has any relation to this detention. It was simply very bad luck.
Except for the initial scare, I have not felt worried at any time. I’m not afraid because I haven’t done anything wrong. They can check my computer and my phone if they want. They won’t find anything that could be considered a crime.

Fernando is completely pale and hasn’t said a word since they brought us to this room. Rich, on the other hand, is very calm. He is always calm. He says it must have been a mistake. In our building, many apartments are rented out and many people are just passing through. Most likely, they entered the wrong apartment. I agree.
The worst part is not knowing what is happening or how long we will have to wait. They confiscated our phones, so we don’t have much to do. Rich’s suggestion is that we spend some time improving my Java knowledge. I don’t really feel like it, but that will keep our minds occupied.
It seems the next topic is conditionals. According to Rich, this will help us improve our programs a lot. He says it’s a fun and easy topic to learn, so my morale has greatly increased. Let’s get to it as soon as possible.
Working with Conditionals
Importance of Conditionals in Java
Conditionals allow programs to make decisions based on different situations. Without them, programs would follow a strict series of steps, unable to adapt to changes or different types of data. Conditionals make the code more flexible, which is essential for creating interactive and functional applications.
Thanks to conditionals, programmers can make their programs respond to what the user does, changes in the environment, or real-time data. This is very important for developing useful applications in the real world, as they allow programs to handle different situations based on variables entered by the user.
For example, in a banking application, conditionals are necessary to verify transactions and validate the information entered by the user. They also help maintain system security. In video games, conditionals control how the game reacts to player actions, making the experience more dynamic and interactive.
Basic Structure of an if
An “if” is a way to tell our program to do something only if a specific condition is met. Think of it like making decisions in everyday life. For example, “If it is raining, take an umbrella.” In programming, it is written similarly:
if (condition) {
// Code that runs if the condition is true
}
- if: This keyword indicates the start of a condition.
- Condition: Inside the parentheses, we write the condition we want to check. For example, “if a number is greater than 10.”
- Code inside braces { }: Inside the braces, we write the code we want to execute if the condition is true.
Let’s see it with a very simple example. Imagine you are creating a program and want it to say “It’s a big number” if a number is greater than 10. Here’s how you should write the code:
int number = 15;
// We have defined a number
if (number > 10) {
System.out.println("It's a big number");
}
- As you can see, the first thing we did was define a number and give it the value 15.
- Then we want it to understand that we want it to perform an action, but only if the number is greater than 10. if (number > 10): Here we are saying “if the number is greater than 10.”
- Finally, we create a line using System.out.println that will print on the screen if the condition is true.
Therefore, if number is greater than 10 (in this case, 15 is greater than 10), the computer will print “It’s a big number”; if it is smaller, it simply won’t do anything at all.
else and else if Statements
When we use if, we can tell our program to do something if a condition is true. But what happens if that condition is not met? That’s where else and else if statements come in.
– “Else”
The else statement is used to specify a block of code that will run if the if condition is not true. It’s like saying: “If the condition is not met, do this instead.”
int number = 15;
if (number > 10) {
System.out.println("It's a big number");
} else {
System.out.println("It's a small number");
}
Above we see the previous example but slightly modified. If the number is greater than 10, it will show “It’s a big number.” Exactly the same as in the previous program, but before if a number was less than 10 it did nothing, now it will show the following text: “It’s a small number.”
– “Else if”
The else if statement is used to check another condition if the first if condition is not met. It’s like saying: “If the first condition is not met, try this other condition.”
int number = 15;
if (number > 10) {
System.out.println("It's a big number");
} else if (number > 5) {
System.out.println("It's a medium number");
} else {
System.out.println("It's a small number");
}
We repeat the same example again. Only now there are not two conditionals but three. The example speaks for itself. The first time we use an else if because we still want to propose one more condition. The second time, a simple else, since it is the last condition we need to state.
Nested Conditionals
Explaining what nested conditionals are is simple; understanding them might be a bit harder, but here we go. Nested conditionals mean placing an if statement (or else if or else) inside another if statement. This allows creating more complex decisions by checking multiple conditions.
To avoid getting completely confused, it’s best to explain it directly with an example. Pay attention, as the code starts to get a bit more complex.
Let’s create a program that tells us:
- If the number is greater than 10.
- If the number is greater than 5 but less than or equal to 10.
- If the number is greater than 2 but less than or equal to 5.
- If the number is less than or equal to 2.
// For this example, we assume the number to consider is 3.
// But it would work the same with any number.
int number = 3;
if (number > 10) {
System.out.println("The number is greater than 10");
} else {
if (number > 5) {
System.out.println("The number is greater than 5 but less than or equal to 10");
} else {
if (number > 2) {
System.out.println("The number is greater than 2 but less than or equal to 5");
} else {
System.out.println("The number is less than or equal to 2");
}
}
}
That’s the code, now let’s analyze it in parts.
First if
condition:
- We check if
number
is greater than 10. - If true, it prints:
→"The number is greater than 10"
- If false, it enters the
else
block.
Second if
condition (nested inside the first else
):
- We check if
number
is greater than 5. - If true, it prints:
→"The number is greater than 5 but less than or equal to 10"
- If false, it enters the next
else
block.
Third if
condition (nested inside the second else
):
- We check if
number
is greater than 2. - If true, it prints:
→"The number is greater than 2 but less than or equal to 5"
- If false, it prints:
→"The number is less than or equal to 2"
Making a side note and realizing that in this case theory is much harder than practice, I would like to give you some advice. Always keep your code as simple and clean as possible. Although I understand that sometimes, depending on the complexity of the program, it may be impossible or at least very difficult.
If we have to deal with situations where we need to use many nested conditionals, it’s best to use else if. Look at this example where the code is much clearer:
int number = 3;
if (number > 10) {
System.out.println("The number is greater than 10");
} else if (number > 5) {
System.out.println("The number is greater than 5 but less than or equal to 10");
} else if (number > 2) {
System.out.println("The number is greater than 2 but less than or equal to 5");
} else {
System.out.println("The number is less than or equal to 2");
}
Even explaining it is easier:
- First if condition:
We check if number is greater than 10.
- First else if condition:
If number is not greater than 10, we check if it is greater than 5.
- Second else if condition:
If number is not greater than 5, we check if it is greater than 2.
Else condition:
- If none of the previous conditions is true, we execute this block.
Using else if, we can make our code more readable and easier to understand. This is very useful for making decisions based on multiple criteria.
Switch case
The switch-case in Java is a conditional structure used when we have several possible options and want to execute different blocks of code depending on the value of a variable. It is a simpler way to write than a bunch of chained if-else statements.
In a switch, the variable we are evaluating is compared with several values called cases. If it finds a match, it executes the code corresponding to that case. If it doesn’t find matches, we can use a default, which is like a “plan B”: the code in default will run if none of the other options are met.
Let’s see it with a simple example. We create a program that tells the user what day of the week it is according to a number from 1 to 7 (1-Monday, 2-Tuesday, etc.). We use switch-case to decide which day corresponds to each number.
public class Main {
public static void main(String[] args) {
int day = 3; // Suppose the user enters the number 3
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid number");
break;
}
}
}
Comparison Operators
Operators will not only be useful with conditionals; from now on, you will use them in practically all programs and exercises you do. Therefore, pay attention and keep this table in mind. I assure you that you will need it soon, and until you memorize it, you will have no choice but to come back and take a look.
a == b: Checks if a is equal to b.
a != b: Checks if a is different from b. a > b: Checks if a is greater than b.
a >= b: Checks if a is greater than or equal to b. a < b: Checks if a is less than b.
a <= b: Checks if a is less than or equal to b.
Logical Operators
The same goes for logical operators: you will see them a lot and they are fundamental if you want to program in Java. However, I consider them perhaps a bit harder to understand than comparison operators. That’s why, after showing you the table, I will show you a small example.
- && (Logical AND)
a && b: Checks if both conditions a and b are true.
- || (Logical OR)
a || b: Checks if at least one of the conditions a or b is true.
- ! (Logical NOT)
!a: Inverts the logical value of a.
public class Main {
public static void main(String[] args) {
int a = 6;
// Logical OR
// We will use || to see if a is odd or greater than 8.
if (a>8 || a%2==0) {
System.out.println("a is even or greater than 8" );
} else System.out.println("a does not meet either condition");
// Logical AND
// We will use && to see if a is even and also greater than 8.
int b = 10;
if (b>8 && b%2==0) {
System.out.println("b is even and greater than 8" );
} else System.out.println("b does not meet one of the two conditions");
// Logical NOT
// We use this operator to invert the logical value
// For variables a and b we want them to be even. For this one, odd.
int c = 7;
if (c%2!=0) {
System.out.println("c is odd" );
} else System.out.println("c is even" );
}
}
Let’s see another example:
int x = 5;
int y = 10;
// Logical AND with comparison operators
if (x < 10 && y > 5) {
System.out.println("x is less than 10 and y is greater than 5");
}
// Logical OR with comparison operators
if (x < 10 || y < 5) {
System.out.println("At least one of the conditions is true");
}
// Logical NOT with comparison operators
if (!(x > 10)) {
System.out.println("x is not greater than 10");
}
- x < 10 && y > 5: Checks if x is less than 10 and y is greater than 5. Both conditions are true, so the message is printed.
- x < 10 || y < 5: Checks if x is less than 10 or y is less than 5. The first condition is true, so the message is printed.
- !(x > 10): Checks if x is not greater than 10. The original condition x > 10 is false, so !(x > 10) is true and the message is printed.
Summary of What We’ve Learned
Conditionals in Java are absolutely necessary for programs to make decisions based on different scenarios. Without conditionals, programs would follow rigid instructions and could not adapt to changes or diverse data. Conditionals add flexibility and dynamism, allowing the creation of interactive and functional applications that respond to user actions, changes in the environment, or real-time data.
The basic structure of a conditional in Java starts with the keyword “if,” followed by a condition that is checked. If the condition is true, the specified code runs. If the condition is not met, “else” and “else if” statements can be used to handle other possible situations, providing alternative code blocks as needed. Nesting conditionals allows for more complex decisions by checking multiple conditions within others.
Another slightly less intuitive structure is switch-case. We could say it is a simpler way to write than a bunch of chained if-else statements. The main advantage of this structure is its simplicity when there are multiple possible options.
Additionally, we have analyzed comparison and logical operators, since without them we couldn’t work with conditionals. Comparison operators include ==, !=, >, >=, <, and <=.
Logical operators, such as && (AND), || (OR), and ! (NOT), allow combining and manipulating conditions, making the code more dynamic and efficient. Using these operators, we can perform complex checks and make decisions based on multiple criteria.
Although at this point the theory may seem a bit overwhelming, with the exercises we have solved you should have no problem handling these operators. Once you complete the other exercises proposed for this topic, you will see that you will have no doubts left.
To make your life easier, I leave you again the list of all operators. Keep it in mind, as it will be very useful:
Operator | Description |
+ | Adds two values |
– | Subtracts two values |
* | Multiplies two values |
/ | Divides the first value by the second |
% | Returns the remainder of integer division |
++ | Increments the variable’s value by 1 |
— | Decrements the variable’s value by 1 |
+= | Adds the specified value to the variable |
-= | Subtracts the specified value from the variable |
*= | Multiplies the variable by the specified value |
/= | Divides the variable by the specified value |
== | Checks if two values are equal |
!= | Checks if two values are not equal |
> | Checks if the first value is greater than the second |
< | Checks if the first value is less than the second |
>= | Checks if the first value is greater than or equal to the second |
<= | Checks if the first value is less than or equal to the second |
&& | Logical AND operator |
|| | Logical OR operator |
! | Logical NOT operator |
?: | Ternary (conditional) operator |
instanceof | Checks if an object is an instance of a class |