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
Boolean isActive = true;— one starting fact.Boolean hasBalance = false;— another starting fact.- (blank line)
Boolean canPurchase = isActive && hasBalance;—&&(AND) needs both sides true — sincehasBalanceisfalse, the whole expression isfalse.Boolean needsReview = isActive || hasBalance;—||(OR) needs at least one side true —isActivealone makes thistrue.Boolean isInactive = !isActive;—!(NOT) flips a Boolean —!trueisfalse.
A real business example: Insurance
Boolean policyIsActive = true;
Integer daysUntilExpiry = 15;
Boolean needsRenewalReminder = policyIsActive && daysUntilExpiry <= 30;
System.debug(needsRenewalReminder); // true
Boolean policyIsActive = true;— one fact about the policy.Integer daysUntilExpiry = 15;— another fact.- (blank line)
Boolean needsRenewalReminder = policyIsActive && daysUntilExpiry <= 30;— combines a Boolean and a comparison with&&: both "is active" and "expiring within 30 days" must be true.System.debug(needsRenewalReminder);— logstrue, since both conditions hold.
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
Leaderboard
- 1. Monde Masiza 2/2
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.