• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Conditional Statements
  4. If Statements

      If Statements

      If Statements

      Up to now your code has run every line from top to bottom, in order. An if statement changes that. It lets your program make a decision: run a block of code only when a condition is true, and skip it otherwise.

      The Basic Shape

      An if statement has a condition inside parentheses and a block of code inside curly braces:

      Integer temperature = 105;
      
      if (temperature > 100) {
          System.debug('It is very hot today.');
      }
      

      The condition temperature > 100 is a Boolean expression. When it is true, the code inside the braces runs. When it is false, that code is skipped and the program continues after the closing brace.

      The Condition Must Be Boolean

      Any expression that produces true or false can be a condition. You can compare values, or use a Boolean variable directly:

      Boolean isWeekend = true;
      
      if (isWeekend) {
          System.debug('Time to relax.');
      }
      

      Code After the If Still Runs

      Only the block inside the braces is conditional. Lines after the closing brace always run, no matter what the condition was:

      Integer balance = 50;
      
      if (balance < 100) {
          balance = balance + 10; // runs only when balance is under 100
      }
      
      System.debug(balance); // this line always runs
      

      Common Mistakes

      • Do not put a semicolon right after the condition: if (x > 0); creates an empty block and the following braces always run.
      • Always use == to compare inside a condition, never a single =, which is assignment.

      An if statement is the foundation of every decision your code will ever make.

      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