Beginner 15 min read

Logical Operators in Practice

By the end of this lesson, you'll be able to:

  • Combine multiple conditions inside an if statement using && and ||
  • Use ! to invert a condition inside an if statement
  • Read a compound if condition and explain what it requires

Prerequisites: "If, Else If, and Else"

Combining conditions inside an if

Boolean isActive = true;
Integer daysOverdue = 15;

if (isActive && daysOverdue > 10) {
    System.debug('Send overdue payment reminder');
}
  1. Boolean isActive = true; — one fact.
  2. Integer daysOverdue = 15; — another.
  3. (blank line)
  4. if (isActive && daysOverdue > 10) { — && requires both sides true — isActive is true and 15 > 10 is true, so the whole condition is true.
  5. System.debug('Send overdue payment reminder'); — runs.
  6. } — closes the if block.

Both conditions must be true for the reminder to trigger — exactly the same && from Module 4, just now directly shaping an if statement's behavior.

A real business example: Loan Processing

Decimal creditScore = 720;
Decimal existingDebt = 15000;

if (creditScore >= 650 || existingDebt < 5000) {
    System.debug('Pre-approved for review');
}
  1. Decimal creditScore = 720; — the applicant's credit score.
  2. Decimal existingDebt = 15000; — their existing debt.
  3. (blank line)
  4. if (creditScore >= 650 || existingDebt < 5000) { — || only needs one side true — 720 >= 650 is true, so the whole condition is true regardless of the debt check.
  5. System.debug('Pre-approved for review'); — runs.
  6. } — closes the if block.

This encodes "either a decent credit score OR low existing debt is enough to pre-qualify" — a realistic underwriting shortcut expressed in one line thanks to ||.

Common mistakes

  • Confusing && and || under pressure. && requires everything to be true; || requires just one. When a compound condition isn't behaving as expected, this mix-up is the first thing worth checking.

Exercise

Declare Boolean isVip = false and Decimal cartTotal = 120. Debug 'Free shipping' if the customer is VIP OR the cart total is at least 100.

Show hint

isVip || cartTotal >= 100

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Logical Operators in Practice Quiz

1. For isActive && daysOverdue > 10 to be true, what must hold?

Log in to submit the quiz and save your score.

Leaderboard

  • 1. Monde Masiza 1/1

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

Module 4's &&, ||, and ! operators become genuinely useful once they're driving real if statements — most real business rules need more than one condition at once.