ApexSensei

Drills Apex basics

Combine conditions with && and ||

Apex basics · Beginner · 10 min · Runs in your Salesforce Developer org · Free

Write `isUrgentOpen(String priority, Boolean sev1, String status)` that returns `true` when a Case is both urgent (High priority or sev1) and still open (status not `Closed`). Combine the two urgent checks with `||`, group them in parentheses, then join to the status check with `&&`.

Lesson

Why this matters

Real business rules almost never fit one check. "Urgent" means High priority or sev1. "Needs action" means urgent and still open. If you can combine && and || correctly, you can turn an English rule into one line of Apex instead of a tangle of if statements.

The smallest working example

Boolean urgent = (priority == 'High' || sev1) && status != 'Closed';

For priority = 'High', sev1 = false, status = 'New', urgent is true.

Name the parts

  • **&&** is Apex's "and". Both sides must be true.
  • **||** is Apex's "or". Either side being true is enough.
  • Parentheses force the order. A || B && C is read as A || (B && C). If you want "(A or B) and C", you must write the parentheses yourself.
  • Apex short-circuits: once (priority == 'High' || sev1) is true, it still has to check the right side of &&, but once && sees false on the left, it skips the right side.

A common wrong version

Boolean urgent = priority == 'High' || sev1 && status != 'Closed';

Without parentheses, this reads as priority == 'High' || (sev1 && status != 'Closed'). A Closed High-priority Case returns true, which breaks the "Closed overrides" rule.

The fix

Wrap the "or" half in parentheses, so the && with status applies to the whole urgent half:

return (priority == 'High' || sev1) && status != 'Closed';

Now you try

Return that one expression from isUrgentOpen. The grader tries open and closed cases, High and Low priority, sev1 on and off.

Learn more

The challenge

Write isUrgentOpen(String priority, Boolean sev1, String status) that returns true when the Case is urgent (High priority or sev1) and still open (status is not Closed).

Examples:

  • isUrgentOpen('High', false, 'New') → true
  • isUrgentOpen('High', true, 'Closed') → false
  • isUrgentOpen('Low', false, 'New') → false

Requirements:

  1. isUrgentOpen('High', false, 'New') should be true.
  2. isUrgentOpen('Low', true, 'Working') should be true.
  3. isUrgentOpen('High', true, 'Closed') should be false.
  4. isUrgentOpen('Low', false, 'New') should be false.
  5. isUrgentOpen('Medium', true, 'Escalated') should be true.
  6. isUrgentOpen('High', false, 'Closed') should be false.
  7. isUrgentOpen('Low', true, 'Closed') should be false.

Starter code

Boolean isUrgentOpen(String priority, Boolean sev1, String status) {
    return null;
}

Related drills

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Count Leads by Rating with a Map · Safe navigation with ?. ›