Codiqo

Learn Java · lesson 14 of 61 · about 7 minutes

if and else

Let the ticket desk act on its answer: run code only when a condition is true, give an alternative with else, and keep every branch in braces.

What you'll learn

  • Write an if statement
  • Add an else branch
  • Use braces for every branch

Doing something about it

Your ticket desk knows whether a booking can go ahead, and canBook holds the answer, but nothing happens yet. if (condition) { ... } runs its block only when the condition is true, and else { ... } runs otherwise. The condition goes in round brackets, and each block goes in braces.

The booking goes ahead, or it doesn't

public class Main {
    public static void main(String[] args) {
        boolean canBook = true;
        int seatsLeft = 116;
        int extra = 3;
        if (canBook) {
            seatsLeft -= extra;
            System.out.println("Booked! Seats left: " + seatsLeft);
        } else {
            System.out.println("Sorry, " + extra + " seats can't be booked");
        }
        System.out.println("Next customer, please.");
    }
}

Output

Booked! Seats left: 113
Next customer, please.

Always use braces

Without braces, an if only guards the one statement after it. Indenting a second line doesn't put it inside: Java ignores indentation. Worse, an else after two unbraced lines doesn't compile at all, because the if already ended. Braces on every branch avoid both problems, even when a branch is one line long.

Tip

In Java the condition must be a real boolean. if (extra) with an int doesn't compile: write the question out, like if (extra > 0).

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.