Notes
The break
statement can be used to jump out of a loop.
for (Integer i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.debug(i);
}
Output: 0 1 2 3
The continue
statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
for (Integer i = 0; i < 6; i++) {
if (i == 4) {
continue;
}
System.debug(i);
}
Output: 0 1 2 3 5
You can also use break and continue in while loops:
Integer i = 0;
while (i < 10) {
System.debug(i);
i++;
if (i == 4) {
break;
}
}
Output: 0 1 2 3
Integer i = 0;
while (i < 6) {
if (i == 4) {
i++;
continue;
}
System.debug(i);
i++;
}
Output: 0 1 2 3 5