ApexSensei

Drills Apex basics

break and continue

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

Write `countPositivesUntilZero(List<Integer> numbers)` that walks the list, counts every number greater than zero, skips `null` with `continue` and stops at the first `0` with `break`. Negative numbers do not count but keep the loop going.

Lesson

Why this matters

Most loops do not need to walk every element: you want to skip the broken ones and stop when you reach a sentinel. continue and break are the two Apex keywords for that, and they keep your logic flat instead of nested in if after if.

The smallest working example

Integer count = 0;
for (Integer n : numbers) {
    if (n == null) {
        continue;
    }
    if (n == 0) {
        break;
    }
    if (n > 0) {
        count++;
    }
}

Name the parts

  • **continue** jumps to the next iteration. The rest of the body is skipped.
  • **break** leaves the loop entirely. No more iterations run.
  • The order of your checks matters. null is tested first, then 0, then positive. null > 0 is false, not an exception. Test null first with continue so the skip is explicit.

A common wrong version

for (Integer n : numbers) {
    if (n > 0) {
        count++;
    } else if (n == 0) {
        break;
    }
}

For n = null, n > 0 is false, so the null is not counted and the loop does not stop. continue makes that skip explicit.

The fix

Check null first and continue; check 0 next and break; only then increment on positives.

Now you try

Finish countPositivesUntilZero so it returns the number of positives seen before the first 0, skipping null and ignoring negatives.

Learn more

The challenge

Write countPositivesUntilZero(List<Integer> numbers) that counts positives in order, skipping null with continue and stopping at the first 0 with break.

Examples:

  • countPositivesUntilZero(new List<Integer>{ 1, 2, 3 }) → 3
  • countPositivesUntilZero(new List<Integer>{ 1, 0, 2 }) → 1
  • countPositivesUntilZero(new List<Integer>{ null, 1, 2 }) → 2

Requirements:

  1. countPositivesUntilZero(new List<Integer>{ 1, 2, 3 }) should be 3.
  2. countPositivesUntilZero(new List<Integer>{ 1, 0, 2 }) should be 1.
  3. countPositivesUntilZero(new List<Integer>{ null, 1, 2 }) should be 2.
  4. countPositivesUntilZero(new List<Integer>{ -1, 1, 2 }) should be 2.
  5. countPositivesUntilZero(new List<Integer>()) should be 0.
  6. countPositivesUntilZero(new List<Integer>{ null, 0, 5 }) should be 0.
  7. countPositivesUntilZero(new List<Integer>{ 5, 5, 5 }) should be 3.

Starter code

Integer countPositivesUntilZero(List<Integer> numbers) {
    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.

‹ Safe navigation with ?. · Find the compile error ›