Introduction

Conditional statements allow programs to execute certain code based on one or more conditions. So far, we’ve only written programs in which every line of code gets executed once, but almost all software needs to make a decision at some point. We may want some code to run in one situation but not in another, or we may want code run multiple times. For these situations we use conditionals.

Expressions and Booleans

Before we look at conditionals, let’s talk more about the boolean data type and its two possible values, true and false. We can type the words true and false directly in the code, and even print them:

public class Booleans1 {
    public static void main(String[] args) {
        System.out.println(true);
        System.out.println(false);
    }
}
[Run]
true
false

This program seems reasonable, and it is, but remember that the keywords true and false represent booleans in Java, meaning println has to convert them to Strings before they’re printed. In other words, true is different to "true" and false is different to "false". The keywords true and false are booleans, but "true" and "false" are strings of characters.

Expressions can produce true or false when using certain operators. For instance, the == (double-equals) means “equal to”. It compares two values and returns true if the values are equal and false if they are not equal. For example, the expression 10 == 10 is true because 10 is equal to 10, whereas 10 == 5 is false because 10 is not equal to 5, ergo it’s a false expression.

public class Booleans2 {
    public static void main(String[] args) {
        System.out.println(10 == 10);
        System.out.println(10 == 5);
    }
}
[Run]
true
false

The expressions in the parentheses produce a result (true or false) and the print statements simply print it. There are six types of these operators:

OperatorMeaning
==equal to
!=not equal to
greater than
>=greater than or equal to
less than
<=less than or equal to

The != operator means not equal to. It does the opposite of ==. For example:

  • 12 != 9 (12 is not equal to 9) is true, because 12 does not equal 9.
  • 12 != 12 (12 is not equal to 12) is false, because 12 does equal 12.

The > and < operators mean greater than and less than, respectively. The > evaluates to true if the left number is greater than the right number, otherwise false. The < evaluates to true if the left number is less than the right number, otherwise false. For example:

  • 12 > 9 (12 is greater than 9) is true.
  • 12 < 9 (12 is less than 9) is false.
  • 12 < 12 (12 is less than 12) is false.

The <= means less than or equal to. It returns true if the left number is less than or equal to the right number, otherwise false. The >= means greater than or equal to. It returns true if the left number is greater than or equal to the right number, otherwise false. For example:

  • 98 <= 86 is false.
  • 7 <= 86 is true.
  • 283 >= 283 is true.
  • 105 <= 104 is false.
  • 105 >= 104 is true.

If-then Statements

If-then statements, or simply if statements, rely on booleans to decide whether or not certain code is to be executed. They are named as such due to their function: if a condition is true, then run some code. An if statement looks like this:

if (condition) {
    code goes here
}

As we can see, an if statement starts with the word if. Following this are two parentheses that contain the condition, which can either be true or false. Next are two curly brackets {}, which represent the body of the if statement and contain normal code. If the condition is true, the code in the body will run. If the condition is false, the code in the body will not run. Here is an example:

public static void main(String[] args) {
   System.out.println("Apple");
  
   if (true) {
       System.out.println("Orange");
       System.out.println("Cherry");
   }

   System.out.println("Banana");
}
[Run]
Apple
Orange
Cherry
Banana

On line 2, “Apple” is printed. Next is an if statement starting on line 4. First, the condition is checked to see whether it’s true or false. It’s true, therefore the body is executed, so line 5 prints “Orange” and line 6 prints “Cherry”. Line 7 is the end of the if statement and the program continues as normal. Finally, on line 9, “Banana” is printed.

What happens if we change the condition to false?

public static void main(String[] args) {
   System.out.println("Apple");

   if (false) {
      System.out.println("Orange");
      System.out.println("Cherry");
   }

   System.out.println("Banana");
}
[Run]
Apple
Banana

On line 2, “Apple” is printed the same as before. On line 4, the condition is checked. It’s false this time, so the body is skipped over and the program continues on to line 9 and prints “Banana”.

As you may have guessed, instead of writing true or false in the condition we can write expressions. For example:

if (3 < 7) {
    System.out.println("Orange");
}

3 < 7 evaluates to true so the if statement runs and “Orange” gets printed. On the other hand:

if (6 < 9) {
    System.out.println("Orange");
}

6 > 9 evaluates to false so the if statement is skipped and “Orange” does not get printed.

Note that code in an if statement works exactly the same as code outside an if statement. The code is still executed from top to bottom. The only difference is that the code outside is guaranteed to run whereas code inside is dependent on the condition being true. Also, pay attention to the indentation of the code. Since some of the print statements are nested in the if statement, they are indented even further to the right than the other statements. You should always indent statements relative to their position within the code, for the sake of readability. This will come naturally to you as you read and write more code.

You Must Be This Tall

Imagine there’s a machine at the entrance of a rollercoaster into which customers must enter their height. The program running on the machine will tell the customer whether or not they can ride the rollercoaster based on their height. The minimum height to ride the rollercoaster is 130cm. The following program is the first version.

import java.util.Scanner;

public class IfStatements1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Welcome to SuperFast Rollercoaster!");
        System.out.print("Please enter your height in centimetres: ");
        int height = sc.nextInt();

        if (height < 130) {
            System.out.println("Sorry, you cannot ride as you are too short.");
        }
    }
}
[Run]
Welcome to SuperFast Rollercoaster!
Please enter your height in centimetres: 126
Sorry, you cannot ride as you are too short.

Line 5 sets up a Scanner. Line 7 prints a welcome message to the user. Line 8 prompts the user to enter their height. Line 9 stores the input in variable height. Line 11 then checks if height is less than 130. In the sample run, 126 is entered, and the expression 126 < 130 is true, therefore line 12 runs and prints “Sorry, you are too short.”

What if we enter 133?

[Run]
Welcome to SuperFast Rollercoaster!
Please enter your height in centimetres: 133

Not much happens. The expression 133 < 130 is false, therefore the if statement doesn’t run and the program ends like normal. In that case, let’s add another if statement to tell the user they can go ahead if they meet the requirements.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to SuperFast Rollercoaster!");
    System.out.print("Please enter your height in centimetres: ");
    int height = sc.nextInt();

    if (height < 130) {
        System.out.println("Sorry, you cannot ride as you are too short.");
    }

    if (height >= 130) {
        System.out.println("Your height is acceptable. Go ahead.");
    }
}
[Run 1]
Welcome to SuperFast Rollercoaster!
Please enter your height in centimetres: 141
Your height is acceptable. Go ahead.
[Run 2]
Welcome to SuperFast Rollercoaster!
Please enter your height in centimetres: 119
Sorry, you cannot ride as you are too short.

In this program, the second if statement (lines 12-14) basically does the opposite of the first (lines 8-10). The first one runs if the height is less than 130 and the second one runs if the height is greater than or equal to 130. The two conditions are mutually exclusive meaning it’s impossible for both to run on a single execution. In Run 1 above, since 141 was entered, only the if statement on line 12 runs and line 13 prints “Your height is acceptable. Go ahead.” In Run 2, since 119 was entered, only the if statement on line 8 runs and line 9 prints “Sorry, you cannot ride as you are too short.”

Syntactically, the two if statements are two discrete blocks of code (like building blocks), but a single if statement can be composed of multiple blocks if necessary. The if block, as used in the program, is just one type of block. There’s also the else if block and the else block. The problem with the current program is that both if blocks get checked regardless of the input. For example, say 125 is entered for the height, the first if block checks if height < 130. This is true, and it tells the customer they are too short to go on the ride. The program could end right there. There is no need to go on to the second if block and check if height >= 130 because it’s guaranteed to be false. This wastes processing time (which is all but irrelevant), but more importantly it takes more mental power from us to form an understanding of the code. So, instead of using two if statements composed of one block, we can use one if statement composed of two blocks, so that the two blocks are logically connected.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to SuperFast Rollercoaster!");
    System.out.print("Please enter your height in centimetres: ");
    int height = sc.nextInt();

    if (height < 130) {
        System.out.println("Sorry, you cannot ride as you are too short.");
    }
    else if (height >= 130) {
        System.out.println("Your height is acceptable. Go ahead.");
    }
}

Lines 8-13 are a single if statement composed of an if block and an else if block. Naturally, the blocks and their conditions are always checked from top to bottom, but only one of the blocks can run because if statements are either-or constructs. For example, if 125 is entered, the if block (lines 8-10) is checked. It’s true so it runs. The program will then skip over the else if block (lines 11-13) without checking it at all. On the other hand, if 134 is entered, the if block is checked, it’s false, so the else if block is checked. It’s true so it runs.

Again, blocks that come before other blocks take precedence. Even if multiple conditions were to be true, only the foremost block would run. It’s also possible that no blocks will run if all the conditions are false. Although, in this program that would be mathematically impossible.

We can simplify the program even further. Currently, if the if block is false, that means the height must be greater than 130, which means the else if condition is redundant because it’s guaranteed to be true. This means we can replace it with an else block:

public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);

   System.out.println("Welcome to SuperFast Rollercoaster!");
   System.out.print("Please enter your height in centimetres: ");
   int height = sc.nextInt();

   if (height < 130) {
       System.out.println("Sorry, you cannot ride as you are too short.");
   }
   else {
       System.out.println("Your height is acceptable. Go ahead.");
   }
}

Line 11 is now an else block. An else block is like a fallback block—it does not have a condition because it will always run if none of the other blocks run above it.

Let’s add another height restriction. The ride allows a maximum height of 210cm. For this, we can add an else if block in between:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to SuperFast Rollercoaster!");
    System.out.print("Please enter your height in centimetres: ");
    int height = sc.nextInt();

    if (height < 130) {
        System.out.println("Sorry, you cannot ride as you are too short.");
    }
    else if (height > 210) {
        System.out.println("Sorry, you cannot ride as you are too tall.");
    }
    else {
        System.out.println("Your height is acceptable. Go ahead.");
    }
}
[Run]
Welcome to SuperFast Rollercoaster!
Please enter your height in centimetres: 216
Sorry, you cannot ride as you are too tall.

Like before, the blocks are always checked in order, from top to bottom. As soon as one evaluates to true, it runs and the rest are skipped. In the sample run, the value 216 is entered. This means the first condition (line 8) is false, but the second one (line 11) is true, so it prints “Sorry, you cannot ride as you are too tall.”. The final block (line 14) is skipped over.

To summarise, the rules about if statements are as follows:

  • An if statement must always have an if block. Any other blocks are optional.
  • An if statement can only ever have one if block and one else block, but can have as many else if blocks as required.
  • The if block must always come first and an else block must always come last. Any else if blocks must go in between.

Leave a Reply

Your email address will not be published. Required fields are marked *