Logical And Short Circuit Operators

Logical operators combine or invert boolean expressions.

OperatorResult is true when...
&&Both sides are true
||At least one side is true
!The following boolean is false

Check two requirements

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasLicense = true;

        boolean canDrive = age >= 18 && hasLicense;

        System.out.println("Can drive: " + canDrive);
    }
}

Output:

Can drive: true

Both conditions are true: the age is at least 18 and hasLicense is true. If either condition were false, canDrive would be false.

Use || when either condition is enough. The ! operator reverses a boolean value, so !hasLicense is true when hasLicense is false.

Short-circuiting matters when the right side performs extra work. With &&, Java skips the right side when the left side is false. With ||, it skips the right side when the left side is true.

Use && and || for conditions. The single-character & and | can operate on booleans too, but they always evaluate both sides.

Check whether a number is positive and even.