AI Hints
Home›Java Tutorial›Logical Operators, The Ternary Operator and switch
Java · Lesson 31 of 120

Logical Operators

And, or, not.

⏱ 2 min read▶ Video at 40:24🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Sometimes one question isn't enough. Are you an adult, and do you have a ticket? Logical operators combine conditions into one.

  • Combine conditions
  • and, or, not
  • One true or false

The three operators

Two ampersands mean and. Both sides must be true. Two vertical bars mean or. At least one side must be true. And an exclamation mark means not. It flips true into false.

keyvalue
&&and: both true
||or: at least one true
!not: flips it
Resulta boolean

Combining conditions

To enter, you must be an adult, and have a ticket. For a discount, you can be a member, or a child. Not member flips false into true. Run it. Welcome to the concert. Full price, because neither discount condition is true. And not a member, true.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int age = 25;
        boolean hasTicket = true;
        boolean member = false;

        if (age >= 18 && hasTicket) {
            System.out.println("Welcome to the concert!");
        }
        if (member || age < 12) {
            System.out.println("You get a discount.");
        } else {
            System.out.println("Full price.");
        }
        System.out.println("Not a member? " + !member);
    }
}
Output
Welcome to the concert!
Full price.
Not a member? true

Java stops early

And stops checking as soon as one side is false. This is called short circuiting. Here, name is null, which means no string at all. Calling length on null would crash. But the first check is false, so Java never runs the second one. And a range check needs two conditions, joined with and. Run it. No crash, and seven is in range.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String name = null;
        if (name != null && name.length() > 3) {
            System.out.println("Long name");
        } else {
            System.out.println("No name, or a short one");
        }
        int x = 7;
        boolean inRange = x >= 1 && x <= 10;
        System.out.println("1 to 10? " + inRange);
    }
}
Output
No name, or a short one
1 to 10? true

Summary

And needs both sides true, or needs at least one, and not flips a boolean. Java stops checking early, when it knows the answer. Next, a short way to write if and else.

Key takeaways
  • && both
  • || either
  • ! flips
Next up: The Ternary Operator — if and else in one line