• Lessons Home
Topics
Community
  1. Lessons
  2. Arithmetic & Logic
  3. Logical Expressions
  4. Logical Operators

      Logical Operators

      Logical Operators

      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 (!).

      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
      

      Truth Table Quick Reference

      System.debug(true && true);   // true
      System.debug(true && false);  // false
      System.debug(false || true);  // true
      System.debug(false || false); // false
      System.debug(!false);         // true
      

      Combining Comparisons

      The real power comes from combining comparison results into one expression:

      Integer age = 25;
      Boolean hasLicense = true;
      Boolean canRentCar = age >= 21 && hasLicense; // true
      

      Short-Circuit Evaluation

      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
      
      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In