Codiqo

Learn Java · lesson 11 of 61 · about 8 minutes

Logical Operators

Decide whether a booking can go ahead: combine conditions with && (and), || (or) and ! (not).

What you'll learn

  • Combine with && and ||
  • Flip with !
  • Use short-circuiting

Can this booking go ahead?

A booking only works when two things are true at once: the customer asked for at least one seat, and there are enough seats left. That's extra > 0 && extra <= seatsLeft.

and, or, not

  • a && b: both must be true
  • a || b: at least one true
  • !a: flips

Java stops early when it knows the answer, so people != 0 && pizza / people > 2 never divides by zero.

Combining conditions

public class Main {
    public static void main(String[] args) {
        int age = 15;
        boolean hasTicket = true;
        int people = 0;
        System.out.println(age >= 13 && hasTicket);
        System.out.println(age < 12 || age > 65);
        System.out.println(!hasTicket);
        System.out.println(people != 0 && 8 / people >= 2);
    }
}

Output

true
false
false
false

One comparison at a time

In maths you might write 0 < extra ≤ 116. Java can't chain comparisons like that: 0 < extra is already a boolean, and a boolean can't be compared with 116. Write both halves and join them: extra > 0 && extra <= 116.

Too many seats

public class Main {
    public static void main(String[] args) {
        int seatsLeft = 116;
        int extra = 200;
        boolean canBook = extra > 0 && extra <= seatsLeft;
        System.out.println("Booking OK: " + canBook);
        System.out.println("Too many: " + !(extra <= seatsLeft));
    }
}

Output

Booking OK: false
Too many: true

Tip

&& comes before ||, just like × comes before +. When you mix them, add brackets so the order is clear to whoever reads it next.

Now try it yourself

This lesson is free in Codiqo, with 9 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.