• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Loops
  4. Break and Continue

      Break and Continue

      Break and Continue

      Loops normally run until their condition ends them. But sometimes, partway through, you decide you are done early, or that this one item should be skipped. Apex gives you two keywords for exactly that: break and continue.

      Break: Stop the Loop

      break ends the loop immediately. No more passes happen, and control jumps to the code after the loop:

      for (Integer i = 1; i <= 10; i++) {
          if (i == 4) {
              break;
          }
          System.debug(i);
      }
      // Prints 1, 2, 3 and then stops
      

      Use break when you have found what you were looking for and there is no reason to keep going.

      Continue: Skip to the Next Pass

      continue skips the rest of the current pass and jumps straight to the next one. The loop does not stop; it just moves on:

      for (Integer i = 1; i <= 5; i++) {
          if (Math.mod(i, 2) == 0) {
              continue;
          }
          System.debug(i);
      }
      // Prints 1, 3, 5 (even numbers are skipped)
      

      Use continue when the current item should be ignored but the rest still matter.

      Using Both Together

      The two keywords often appear in the same loop. continue filters out items you do not want, and break stops the whole loop when a signal appears:

      for (Integer value : numbers) {
          if (value < 0) {
              continue; // skip this one
          }
          if (value == 99) {
              break;    // stop entirely
          }
          System.debug(value);
      }
      

      Why This Matters

      break and continue let a loop react to its data instead of blindly running to the end. They keep loop logic flat and readable by handling special cases early.

      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