• Lessons Home
Topics
Community
  1. Lessons
  2. Arithmetic & Logic
  3. Logical Expressions
  4. The Ternary Operator

      The Ternary Operator

      The Ternary Operator

      Sometimes your code needs to pick between exactly two values. The ternary operator lets you make that choice in a single expression:

      condition ? valueIfTrue : valueIfFalse
      

      Apex evaluates the condition first. When the condition is true, the whole expression becomes the first value. When it is false, the expression becomes the second value.

      An Expression, Not a Statement

      An if/else statement performs actions, but it does not produce a value. The ternary operator is an expression: it produces a value that you can store in a variable or return from a method.

      Integer temperature = 30;
      String weather = temperature > 25 ? 'Hot' : 'Mild';
      System.debug(weather); // Hot
      

      Side by Side with if/else

      These two blocks of code do exactly the same thing:

      // Using if/else
      String label;
      if (temperature > 25) {
          label = 'Hot';
      } else {
          label = 'Mild';
      }
      
      // Using the ternary operator
      String label2 = temperature > 25 ? 'Hot' : 'Mild';
      

      The ternary version expresses the same choice in one line.

      When to Use It

      Reach for the ternary operator when you have a simple two-way choice between two values. Avoid nesting one ternary inside another: nested ternaries are hard to read, and a plain if/else is much clearer in those cases.

      // Hard to read - do not do this
      String size = value > 100 ? 'Large' : value > 50 ? 'Medium' : 'Small';
      
      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