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.
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
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); }}
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.