A comparison answers one question at a time. Logical operators let you combine several Boolean answers into a single result. Apex has three of them: AND (&&), OR (||) and NOT (!).
&& produces true only when BOTH sides are true.|| produces true when AT LEAST ONE side is true.! flips a Boolean value: !true is false and !false is true.Boolean sunny = true; Boolean warm = false; System.debug(sunny && warm); // false - both must be true System.debug(sunny || warm); // true - one true side is enough System.debug(!warm); // true - NOT flips the value
System.debug(true && true); // true System.debug(true && false); // false System.debug(false || true); // true System.debug(false || false); // false System.debug(!false); // true
The real power comes from combining comparison results into one expression:
Integer age = 25; Boolean hasLicense = true; Boolean canRentCar = age >= 21 && hasLicense; // true
Apex evaluates a logical expression from left to right and stops as soon as the answer is certain. If the left side of && is false, the whole expression must be false, so the right side never runs. If the left side of || is true, the right side never runs. This is called short-circuit evaluation, and it is a handy way to guard against errors:
List<Integer> numbers = new List<Integer>(); // numbers[0] never runs because the left side is false Boolean startsWithTen = !numbers.isEmpty() && numbers[0] == 10; System.debug(startsWithTen); // false, and no error is thrown