Logical Operators
By the end of this lesson, you'll be able to:
- Use &&, ||, and ! to combine or invert Boolean expressions
- Predict the result of a compound logical expression
- Explain short-circuit evaluation at a basic level
Prerequisites: "Comparison Operators"
AND, OR, and NOT
Boolean isActive = true;
Boolean hasBalance = false;
Boolean canPurchase = isActive && hasBalance; // false — both must be true
Boolean needsReview = isActive || hasBalance; // true — at least one is true
Boolean isInactive = !isActive; // false — flips isActive
A real business example: Insurance
Boolean policyIsActive = true;
Integer daysUntilExpiry = 15;
Boolean needsRenewalReminder = policyIsActive && daysUntilExpiry <= 30;
System.debug(needsRenewalReminder); // true
Real business rules are almost always compound like this — "active AND expiring soon" — which is exactly what && expresses directly in code.
Short-circuit evaluation
Apex evaluates && and || left to right, and stops early when the answer is already certain: if the left side of && is false, Apex never bothers checking the right side, since the whole expression is already guaranteed false. This isn't just an optimization detail — it's sometimes used deliberately, for example to safely check record != null && record.Amount > 100 without risking a null pointer error on the second condition.
Exercise
Declare Boolean isPremiumCustomer = true and Integer orderTotal = 45. Declare a Boolean qualifiesForFreeShipping that's true if the customer is premium OR the order total is over 50. Debug it.
Show hint
Use || to combine the two conditions.
Logical Operators Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Logical operators combine multiple Boolean expressions into one: && (AND) requires both sides to be true, || (OR) requires at least one, and ! flips true to false and vice versa.