Learn Java Easy. Chapter 4. Spending Time at the Police Station / Working with Conditionals

Chapter 4. Spending Time at the Police Station / Working with Conditionals

I don’t know how it happened, but I’m at the police station. Specifically, I’m 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 doesn’t make any sense to me. I don’t know exactly what’s happening, or why I’ve been arrested.

 

Shortly after Fernando arrived at the house, the police burst in without warning. Everything happened very quickly. Several armed men entered shouting and ordering us to lie on the floor. They gathered the three of us in the living room and sat us 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 unchecked. The search seemed very thorough.

 

A few minutes after the search began, I saw a police officer come out with our computers. I couldn’t help but think that they had managed to open Chani’s cabinet, while we had spent two days unable to access our things. It didn’t seem fair to me. I also wondered who was going to clean up all that mess. We had just cleaned the whole house and now everything was even worse than after the party. But what kept going through my mind most often was Fernando’s bad luck. He had never come before, and 20 minutes after arriving, the police show up. At no point did I think his visit had anything to do with this arrest. It was simply very bad luck.

 

 

Except for the initial shock, I haven’t felt worried at any point. I’m not afraid, since 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’s always calm. He says it must have been a mistake. In our building, there are many rented apartments and lots of people just passing through. Most likely they entered the wrong apartment. I think the same.    

The worst part is not knowing what’s happening or how long we’ll 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 is going to help us greatly improve our programs. He says it’s a fun and easy topic to learn, so it has greatly increased my morale. Let’s get started on it as soon as possible.

Working with Conditionals

The Importance of Conditionals in Java

 

Conditionals allow programs to make decisions based on different situations. Without them, programs would follow a series of steps strictly, without being able to adapt to changes or different types of data. Conditionals make code more flexible, which is essential for creating interactive and functional applications.

 

Thanks to conditionals, programmers can make their programs respond to user actions, environmental changes, or real-time data. This is very important for developing useful applications in the real world, as they allow programs to handle different situations according to the variables that the user inputs.

 

For example, in a banking application, conditionals are necessary to verify transactions and validate user-entered information. 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 Statement

 

An “if” is a way to tell our program to do something only if a specific condition is met. Think of this like making decisions in everyday life. For example, “If it’s raining, take an umbrella.” In programming, it’s written in a similar way:

 

if (condition) {

            // Code that executes if the condition is true

}

 

  1. if: This keyword indicates the beginning of a condition.
  2. Condition: Inside the parentheses, we write the condition we want to check. For example, “if a number is greater than 10.”
  3. Code between braces { }: Inside the braces, we write the code that we want to execute if the condition is true.

 

Let’s have a look at a very simple example. Imagine you’re creating a program and you want it to say “It’s a big number” if a number is greater than 10. This is 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’ve done is 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’re saying “if the number is greater than 10”.
  • Finally, we create a line using System.out.println that will print to the screen if the condition is true.

 

Therefore, if the number is greater than 10 (in this case, 15 is greater than 10), the computer will print “It’s a big number”; if it’s less, 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 isn’t 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 execute if the if condition is not true. It’s like saying: “If the condition isn’t 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 didn’t do anything, 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 isn’t met, try this other condition”

 

int num = 15;

if (numero > 10) {

    System.out.println("It's a big number");

} else if (numero > 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 aren’t two conditionals but three. The example speaks for itself. The first time we use an else if since we still want to propose one more condition. The second time, a simple else, since it’s the last condition we need to propose.

 

 

Nesting Conditionals

 

Explaining what nesting conditionals means is simple; understanding it might be a bit more difficult, but here we go. Nesting conditionals means placing an if statement (or else if or else) inside another if statement. This allows us to create 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 become 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, let's assume the number we're considering is 3.

// But it would work the same with any number.

int num = 3;

if (num > 10) {

    System.out.println("The number is bigger tan 10");

} else {

    if (num > 5) {

        System.out.println("The number is greater than 5 but less than or equal to 10");

    } else {

        if (num> 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 by parts.

 

  1. First if condition:

 

  • We check if number is greater than 10.
  • If true, we print “The number is greater than 10”.
  • If number is not greater than 10, we enter this else block.

 

2. Second if condition (nested inside the first else):

 

  • We check if number is greater than 5.
  • If true, we print “The number is greater than 5 but less than or equal to 10”.
  • If number is not greater than 5, we enter this else block.

3. Third if condition (nested inside the second else):

 

  •  We check if number is greater than 2.
  • If true, we print “The number is greater than 2 but less than or equal to 5”.
  • If number is not greater than 2, we print “The number is less than or equal to 2”.

 

Making a side note and realizing that in this case, the theory is much harder than the practice, I would like to give you some advice. Keep your code as simple and clean as possible. Although I understand that, in some cases, depending on the program’s complexity, 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 of how the code becomes much clearer:

 

int num = 3;

if (num > 10) {

    System.out.println("The number is greater than 10");

} else if (num > 5) {

    System.out.println("The number is greater than 5 but less than or equal to 10");

} else if (num > 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 simpler:

 

  • 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’s greater than 5.

  • Second else if Condition:

If number is not greater than 5, we check if it’s greater than 2.

  • else Condition:

If none of the previous conditions are true, we execute this block.

 

By 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’s a simpler version to write than a bunch of chained if-else statements.

 

In a switch, the variable we’re evaluating is compared to several values called cases. If it finds a match, it executes the code corresponding to that case. If it doesn’t find any matches, we can use a default, which is like a “plan B”: the code in default will execute if none of the other options are met.

 

Let’s look at a simple example. We’ll create a program that tells the user what day of the week it is based on a number from 1 to 7 (1-Monday, 2-Tuesday, etc.). We’ll use switch-case to decide which day corresponds to each number.

 

public class Main {

    public static void main(String[] args) {

        int day = 3;  // Let's 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 won’t just be useful with conditionals; from now on, you’ll use them in practically all the programs and exercises you do. Therefore, pay attention and keep this table in sight. I assure you that you’ll need it soon, and until you memorize it, you’ll 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 not equal to 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’ll see them everywhere and they are fundamental if you want to program in Java. However, I consider them perhaps somewhat more difficult to understand than comparison operators. That’s why, after showing you the table, I’ll 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;

        // Logic OR

        // We'll 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 doesn't meet either of the two conditions ");

        // Logic AND

        // We'll 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 doesn't meet one of the two conditions");

        // Logic NOT

        // We use this operator to invert the logical value

        // For variables a and b we looked for even numbers. For this one we want 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 prints.
  • 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 prints.
  • !(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 prints.

Did you like it? Donโ€™t keep it to yourself โ€” share it like juicy gossip! ๐Ÿ˜