break وcontinue والتحكم في الحلقة
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
So far a loop ends only when its condition becomes false. Sometimes you want more control. You have found what you were looking for and there is no point running the remaining laps. Or one lap is not worth finishing and you want to jump to the next. Java gives you two statements for that: break and continue.
On the track: break is leaving the track now, mid-lap, and walking home. continue is skipping the rest of this lap and heading straight to the start of the next one, with the counter still moving on.
Why this matters: searching, skipping bad records, and stopping at a sentinel value ("stop when you see 0") are everyday backend patterns. Used well, these two statements make loops shorter. Used badly, they make logic tangled, so this lesson also teaches when not to use them.
This lesson builds on BEG-013-L01 to L03 and on if from BEG-012.
Learning Objectives
By the end of this lesson you will be able to:
- Use
breakto leave a loop immediately. - Use
continueto skip the rest of the current iteration. - Say what happens to the update in a
forloop whencontinueruns. - Say which loop a
breakorcontinueaffects in nested loops. - Use
while (true)withbreakfor a loop that stops in the middle. - Decide when a plain condition is clearer than
breakorcontinue.
Written Explanation
break: leave the loop
break ends the innermost loop (or switch) that contains it. Execution continues with the first statement after the loop. You already met break in BEG-012-L03 inside switch; in a loop it has the same meaning: jump out.
for (int i = 1; i <= 10; i++) {
if (i == 4) break;
System.out.println(i);
}
System.out.println("after");This prints 1, 2, 3, then after. When i is 4, break ends the loop; the println(i) for 4 never runs.
continue: skip to the next iteration
continue ends the current iteration only. The loop does not stop: control goes to the next step of the loop.
- In a
forloop it goes to the update (i++), then the condition check. - In a
whileordo-whileit goes straight to the condition check.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}This prints 1, 2, 4, 5. The Java Tutorials describe continue as skipping the current iteration and moving to the controlling expression of the loop.
The difference is worth burning into memory:
| Statement | Effect on the loop | Rest of the body |
|---|---|---|
break | Ends it | Skipped |
continue | Keeps going | Skipped for this iteration only |
Which loop is affected
In nested loops (more in L05), an unlabeled break or continue acts on the innermost loop only. The outer loop carries on. Java also has labeled breaks that can leave an outer loop; they are rarely needed and we do not use them in this course.
The loop that stops in the middle
Sometimes the natural stopping point is neither at the top nor at the bottom of the body, but halfway through: read a value, and if it is the stop signal, quit; otherwise use it. A while (true) plus break expresses this directly:
while (true) {
int amount = scanner.nextInt();
if (amount == 0) break; // sentinel: 0 ends the input
total += amount;
}A value like 0 here is called a sentinel: a special value that means "stop". The condition true never becomes false, so the break is the only way out. Always check that a break can actually be reached.
Do not change the loop variable in the body
You may be tempted to write i++ or i = 10 inside a for body to skip or to end. Do not: it makes the iteration count hard to predict. Use continue to skip and break to end; both say what you mean.
When not to use them
break and continue are good for clear special cases at the top of the body ("skip invalid", "stop when found"). They are bad when the body has several of them scattered about, because the reader must hunt for every exit. If you have three breaks and two continues, rewrite the condition or move the logic into a method.
Also, the compiler knows that code after an unconditional break or an endless loop cannot run, and it reports an error. We will see that in L06.
Examples
Example 1: skip evens, stop after 7 (simple)
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip evens
if (i > 7) break; // stop after 7
System.out.println(i);
}Output:
1
3
5
7Trace: i = 2, 4, 6 hit continue. i = 9 is odd, so it passes the first if, and then 9 > 7 triggers break. Nothing is printed for 9, 10.
Example 2: find the first multiple (practical)
Find the first multiple of 7 above 50:
int n = 50;
while (true) {
n++;
if (n % 7 == 0) break;
}
System.out.println("First multiple of 7 above 50: " + n);Output:
First multiple of 7 above 50: 56The pattern "search, and stop when found" is the most common use of break. The % remainder operator is from BEG-010-L01. The same search without break would need the condition n % 7 != 0 in the loop header, which is perhaps even clearer; you will often have this choice.
Example 3: sum payments until a sentinel (realistic)
A cash desk reads amounts one per line. A negative number is a mistake that should be ignored, and 0 means "end of the batch":
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int total = 0;
while (true) {
int amount = scanner.nextInt();
if (amount == 0) break;
if (amount < 0) continue;
total += amount;
}
System.out.println("Total " + total);
}
}With the inputs 5, -3, 7, 0 (one per line), the output is:
Total 12-3 is skipped by continue and 0 ends the loop through break, so the total is 5 + 7. Both statements sit at the top of the body, so a reader sees all the special cases first and the normal case last. This "guard clauses first" layout is a good default: the exceptions are dealt with and out of the way before the real work begins. (Real input needs more checks, for example for a word instead of a number; L07 shows one way.)
Backend Insight
Two real situations you will meet:
- Searching. "Find the first order older than 30 days" ends at the first match, not after checking all million. Leaving early with
break(orreturn, which you will learn with methods) saves work, and is the first step toward thinking about cost in BEG-039. - Skipping bad records. In a batch import, a row with a missing field is skipped with
continue, logged, and the import carries on. One bad row should not stop a whole job. Be careful, though: silently skipping hides problems, so real code also records what it skipped.
Another point: a while (true) loop with a break is a loop whose end condition is hidden in the body. In team code, add a comment on the break that says what it means.
Common Mistakes
Mistake 1: Thinking break only leaves the current iteration
- Incorrect: "
breakskips this lap." That iscontinue. - Correct:
breakends the whole loop.
Mistake 2: continue in a while loop that skips the update
int i = 0;
while (i < 5) {
if (i == 2) continue; // i never changes again: infinite loop
i++;
}In a for, continue still runs the update. In a while, the update is in the body, so skipping the body can skip it too. Put the update before the continue, or use a for.
Mistake 3: Expecting break in a nested loop to leave both loops
It leaves only the innermost loop. The outer loop continues with its next iteration.
Mistake 4: Code after break in the same block
Statements after an unconditional break or continue can never run, and the compiler rejects them as unreachable.
Mistake 5: Using many exits
If you cannot explain in one sentence when the loop ends, there are too many breaks. Simplify the loop condition.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. What does this print?
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.print(i + " ");
}أظهر الحل A1
A1. 1 2 then the loop ends at 3.
A2. What does it print if break is replaced by continue?
أظهر الحل A2
A2. 1 2 4 5 : only 3 is skipped.
A3. Which statement ends the loop, and which skips only one iteration?
أظهر الحل A3
A3. break ends the loop; continue skips one iteration.
Level B: Application
B1. Print the numbers 1 to 15 that are not multiples of 5, using continue.
أظهر الحل B1
B1.
for (int i = 1; i <= 15; i++) {
if (i % 5 == 0) continue;
System.out.println(i);
}B2. Starting at 1, print numbers until the square of the number exceeds 50, using while (true) and break. Print only numbers whose squares are 50 or less.
أظهر الحل B2
B2.
int n = 1;
while (true) {
if (n * n > 50) break;
System.out.println(n);
n++;
}It prints 1 to 7 (7 squared is 49; 8 squared is 64).
B3. In the loop below, the programmer wants to skip 3 but the program hangs. Explain why and fix it.
int i = 1;
while (i <= 5) {
if (i == 3) continue;
System.out.println(i);
i++;
}أظهر الحل B3
B3. When i is 3, continue jumps to the condition without running i++, so i stays 3 forever. Fix: increment before continue, or use a for loop:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}Level C: Challenge
C1. Write a loop that reads whole numbers until the user enters -1, ignores any number above 100, and prints the sum of the others and how many were counted.
أظهر الحل C1
C1.
Scanner scanner = new Scanner(System.in);
int sum = 0, count = 0;
while (true) {
int x = scanner.nextInt();
if (x == -1) break;
if (x > 100) continue;
sum += x;
count++;
}
System.out.println(sum + " from " + count + " numbers");C2. A teammate's loop has break in an inner loop and expects the whole program section to stop. What do you tell them, and what simple change gives them what they want?
أظهر الحل C2
C2. An unlabeled break leaves only the innermost loop, so the outer loop carries on. A simple fix without labels: set a boolean such as found = true before the break, and make the outer loop's condition (or its first line) check that flag. Another option, once you know methods, is to put the loops in a method and return.
Mini Challenge
Write a program that prints the numbers 1 to 30 as follows:
- Skip every number divisible by 4 using
continue. - Stop completely when the number is greater than 25 using
break. - After the loop print the last number printed. (Hint: keep it in a variable declared before the loop.)
Check your work: your output has 19 numbers, none divisible by 4, and the last number printed is 25.
Summary & Next Lesson
Key takeaways
breakends the innermost loop immediately;continueskips to the next iteration.- In a
for,continuestill runs the update; in awhile, make sure the update is not skipped. while (true)plusbreakfits loops that end in the middle of the body, such as sentinel input.- Do not change the loop variable inside the body; use
breakandcontinueinstead. - Keep exits few and obvious.
Next lesson
The next lesson, "Nested loops", puts a loop inside a loop to handle rows and columns, and shows how to count how many times the body runs.
Self-check
- What does
breakdo in a loop? - What does
continuedo? - In a
forloop, what runs right aftercontinue? - In nested loops, which loop does an unlabeled
breakleave? - What is a sentinel value?
أظهر الإجابات
- It ends the loop immediately.
- It skips the rest of the current iteration and goes to the next one.
- The update (for example
i++), followed by the condition check. - Only the innermost loop.
- A special value, such as
0or-1, that tells the loop to stop.
References
- Oracle, Branching Statements (Java Tutorials). It supports that an unlabeled
breakends the innermostswitch,for,while, ordo-while, and thatcontinueskips the current iteration and moves to the loop's controlling expression. - Oracle, Java Language Specification, SE 21, Chapter 14. It supports that in a basic
for,continueruns the update before the next condition check. Examples 1 and 2 were compiled and run with JDK 21; Example 3 was run with the piped input shown. The claim that the compiler rejects unreachable statements was confirmed by a compile in L06.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.