Java For Loops, Break, and Continue
Keep repetition control visible, read values in order, skip only the candidates you reject, and stop a search as soon as its answer is known.
Before you start: review while and do-while, switch exits, and Scanner validation. The small arrays below are explained before use; the next lesson covers arrays in depth. All source examples run with Java 21.
What you will be able to do
- Trace initialization, condition, body, and update in their actual execution order.
- Choose counter starts, boundaries, and direction deliberately.
- Use an indexed loop when position matters and an enhanced for when values are enough.
- Explain why continue still reaches a basic for loop's update step.
- Distinguish loop break, switch break, and method return.
- Search finite input, skip invalid readings, and report why processing stopped.
A for loop groups the start, check, and update
The previous lesson separated a counter's starting value, while condition, and update. A basic for loop groups those three control pieces in one header. For a known sequence of practice steps, that makes the intended start and stopping boundary easy to inspect together before reading the work inside the braces.
The header has three parts separated by semicolons: int step = 1 initializes the counter, step <= 3 is the boolean condition, and step++ is the update. The body prints the current step. Read the complete statement as: start at 1, process steps while the value is at most 3, and increase it after each normally completed iteration.
A for loop does not mean that the body must run a predetermined number of times. Its condition is checked repeatedly, and a break can leave early. It is simply a useful structure when the progression belongs naturally in a header. Keep braces around the body and avoid adding a semicolon immediately after the header, which would create an empty loop body.
Main.java · Keep repetition control in one header
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Practice step 1
Practice step 2
Practice step 3
Practice complete.
The update happens after the body, not before the first print
Execution order is initialization once, condition, body, update, then condition again. In the first example, step starts at 1 and the first true check lets the body print 1. Only afterward does step++ change it to 2. Do not read the header left-to-right on every iteration as though initialization keeps resetting the counter.
After printing 3, the update makes step 4. The next condition is false, so execution continues at Practice complete. There are three body executions and four condition checks. Changing the initial step to 4 skips every body execution, but the final completion message still prints.
The counter declared with int in this header is in scope within its condition, update, and body, not after the loop. Printing step afterward causes a compile error. Declare it before the loop only when later work genuinely needs its final value; otherwise the narrower header declaration keeps a temporary counter from leaking into unrelated code.
Trace the three-step loop
- Initialize step to 1 once.
- Check 1 <= 3, print step 1, then update to 2.
- Check 2 <= 3, print step 2, then update to 3.
- Check 3 <= 3, print step 3, then update to 4.
- Check 4 <= 3: false. Skip the body and print Practice complete.
Change the start to 3, then to 4. Explain why these produce one iteration and zero iterations respectively.
Choose the update and comparison as one rule
A for update can count down or move by more than one. The countdown starts at 6, accepts values at least 2, and subtracts 2 each time. Its body therefore sees 6, 4, and 2. The update then produces 0, which fails the next check. No Points: 0 line prints.
The comparison must agree with the direction. Incrementing points while checking points >= 2 moves away from the intended exit. Integer overflow is not a sensible way to terminate an accidental long run. Use small bounded examples and explain the next value after the last valid iteration before increasing a target.
Changing >= 2 to > 2 excludes the final value 2. Changing the starting value to 5 gives 5 and 3, not 6, 4, and 2. A loop follows arithmetic progression, not a human expectation that it will eventually land on a particular number. Test a start already outside the boundary as well as one exactly on it.
Main.java · Count down in steps of two
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Points: 6
Points: 4
Points: 2
Countdown complete.
A small array gives us values to traverse
To compare the two for forms, we need a group of values. int[] scores = {40, 65, 90} creates a fixed-length integer array with three entries. This is a small preview of the next arrays lesson: the brackets in int[] describe the array type, and the brace list supplies its initial values.
An array index is a zero-based position. scores[0] is 40, scores[1] is 65, and scores[2] is 90. scores.length is the number of entries, 3, not the last valid index. That is why the indexed loop starts at 0 and uses index < scores.length rather than <=. Trying position 3 would access beyond the array.
Choose an indexed loop when the output or calculation needs a position, a particular direction, or a chosen stride. Here the position appears in each printed line. An empty array has length zero, so the first check is false and no element access occurs. Avoid assuming every group contains a first value.
Main.java · Read values with their positions
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Index 0: 40
Index 1: 65
Index 2: 90
Scores read: 3
Use enhanced for when you only need each value
Read for (int score : scores) as: for each int value in scores, call the current value score and execute this body. The colon separates the local element variable from the array being traversed. There is no index to initialize or compare, and no manual update to forget.
The total begins at zero outside the loop and receives 40, then 65, then 90. Its final value is 195. The traversal order is the array's element order. If scores is empty, no element body runs and the total remains zero. Enhanced for also supports Iterable objects, which will make more sense in the collections lessons.
For this primitive int array, score receives the current element's value. Assigning score = 0 inside the loop does not replace the corresponding array entry. Use an indexed assignment when you intend to change an element. Also note that the array itself must exist: a null reference is not an empty array and cannot be traversed safely without a check.
Main.java · Read each value without managing an index
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Total: 195
continue skips the rest of this iteration
In the number scan, 3 is deliberately excluded. When number == 3, continue skips the later println in that body. It does not end the entire loop. Values 4 and 5 still reach the printing statement, so the result contains four accepted lines rather than stopping after 2.
For a basic for loop, an unlabelled continue targeting that loop proceeds to its update expressions, then checks the condition again. At number 3, number++ still makes the next value 4. This is different from assuming that continue jumps straight to the condition while leaving the counter unchanged.
Use continue for a clear skip policy such as ignoring an invalid reading. Keep the rejected condition close to the exit and put only accepted work below it. A deeply nested body with many continues can be difficult to follow; sometimes a simple if around the accepted work is easier. Pick the structure whose skipped statements you can explain precisely.
Main.java · Skip one value and keep progressing
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Accepted: 1
Accepted: 2
Accepted: 4
Accepted: 5
Scan complete.
Where does execution go at number 3?
The condition number == 3 is true, so continue skips the Accepted message. Control reaches number++ in the header, producing 4. The next condition succeeds and Accepted: 4 prints. Replace continue with break to see why values 4 and 5 disappear.
break ends a search once its answer is known
The search ignores readings outside 0 through 100 and looks for the first valid value at least 80. The array contains 42, -1, 81, and 95. The first is valid but too low, the second is skipped, and 81 qualifies. After printing 81, break leaves the loop, so 95 is never inspected.
found remembers whether a match was discovered. It starts false and becomes true immediately before break. After the loop, the false case prints a not-found message. Do not infer absence just because a counter reached a particular value; an explicit result flag makes the difference between finding a match and exhausting the values easier to read.
Unlike continue, break does not perform the basic for loop's update before leaving it. Unlike return, it does not leave main. That is why Search complete still prints. This is a first-match search, not a maximum calculation: if 95 appeared before 81, 95 would be the answer because it is encountered first, not because it is the largest value.
Main.java · Stop after the first qualifying reading
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
First high reading: 81
Search complete.
Try a search that finds nothing
Replace the array values with 42, -1, and 79. The invalid -1 is skipped and neither valid value reaches 80, so the not-found message prints. Now put 95 before 81: the answer becomes 95 because the search uses encounter order, not a maximum calculation.
Unlabelled exits target the nearest relevant structure
With a loop inside another loop, a plain break leaves only the innermost enclosing loop or switch. In this seating preview, seat 1 prints and seat 2 triggers break. The inner seat loop finishes, but the row footer and outer row update still happen. The next row starts a fresh inner loop with seat = 1.
The same principle explains the previous lesson's switch inside a while: break in a switch exits that switch, not necessarily the loop surrounding it. continue instead targets the nearest enclosing loop, not a switch. Always identify the exact enclosing structure before deciding which statements are skipped.
You can write labelled exits in Java, but this beginner lesson does not need them. If a nested search becomes difficult to express, a flag or a later helper method can make the intention clearer. For now, trace both the inner and outer updates separately instead of assuming that any break means stop all repetition.
Main.java · An inner break leaves the inner loop
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Row 1, seat 1
Row finished: 1
Row 2, seat 1
Row finished: 2
A while continue does not perform a hidden counter update
A while loop has no update slot. Its continue goes back to the next condition check, so a manual increment placed later in the body can be skipped. If an even value triggers continue before that increment, the same even value may be tested repeatedly without progress.
The safe example copies next to current and increments next before the possible continue. Even numbers skip their printing work, but the next value has already advanced. The body therefore prints 1, 3, and 5, then the while condition rejects next = 6. This is a deliberate progress rule, not an automatic behavior of continue.
When reading input, consuming the current line before validation serves a similar purpose: rejected data must not remain unread at the front. Trace every path that repeats, including empty and invalid inputs. Never use a sandbox timeout as your normal stopping rule; review an unsafe loop without running an unbounded stream of output.
Main.java · A while continue needs deliberate progress
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Odd: 1
Odd: 3
Odd: 5
Next value: 6
Choose the loop that makes the progression obvious
Use basic for when a start, condition, and update naturally describe the traversal. Use enhanced for when you want values in order without needing their positions. Use while when repetition depends mainly on changing state or input availability rather than an explicit counter progression.
Use break when the whole current search is finished, and continue when only the current candidate should be skipped. Neither keyword validates a value on its own: your conditions define valid data. Place counting and summing statements after rejection checks if rejected candidates must not contribute to those results.
Before writing a lab solution, define what each counter measures. Lines read includes rejected input; valid readings excludes it; a matching reading is valid and therefore contributes to that count before the search stops. Those definitions determine where increments belong and prevent an apparently correct final message from hiding inconsistent totals.
Repair exercise: skip a number without ending the sum
Add numbers 1 through 5 but skip 3. The intended total is 12. This program stops too soon. Predict its current total, repair the exit keyword, and keep the update in the for header.
Main.java · Repair a premature exit
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Reveal the explained repair
The original adds 1 and 2, then break ends the loop at 3, producing 3. continue instead skips the addition of 3 but still reaches number++ in the header. The following iterations add 4 and 5, giving 12. With limit 1 the result is 1; with limit 0 the loop runs zero times and the result remains 0. Removing the condition or changing the printed total would hide the defect rather than implement the rule.
Main.java · Repaired selective sum
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Total: 12
Independent lab: find the first high reading
Search up to six input lines for the first valid reading at least 80. A reading must be one whole int value from 0 through 100. Skip bad lines without losing progress, stop immediately on a qualifying reading, and report how much input was actually examined. This is a console data-processing exercise, not a live monitoring integration.
- Use one Scanner and a basic for loop. Process at most six lines, checking hasNextLine before each read. Count every consumed line, including rejected ones.
- Strip the line and parse it with Integer.parseInt. On a parsing failure, print Line N: invalid integer., increment the skipped count, and continue. The catch pattern is provided in the hints.
- Reject values outside 0 through 100 with Line N: outside 0..100., increment the skipped count, and continue.
- For an accepted reading, increment the valid count and print Accepted: followed by its value. If it is at least 80, print First high reading: followed by the value, remember the match, and break.
- After the loop, print Exit: threshold reached if a match was found. Otherwise print Exit: read limit reached if six lines were consumed, or Exit: input ended if fewer were available. A match on line six takes priority over the read-limit reason.
- Finally print Lines read:, Valid readings:, and Skipped readings: with their counts. Do not read or process any lines after the first qualifying reading or beyond the six-line limit.
The prefilled input is bad, -2, 45, 82, and 99 on separate lines. Supply all input before Run; this runner is not a live terminal. Expected output:
Line 1: invalid integer.
Line 2: outside 0..100.
Accepted: 45
Accepted: 82
First high reading: 82
Exit: threshold reached
Lines read: 4
Valid readings: 2
Skipped readings: 2
Main.java · Build your bounded search
Predict the result, edit Main.java, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
Hints before the solution
The initializer starts slot at 1; the condition combines the six-line budget with hasNextLine; the update increments slot. Read and increment linesRead before validating. Parse inside try, with catch (NumberFormatException error) handling a malformed or out-of-int-range line. Increment skippedReadings and continue inside that catch. A second guard rejects values outside the allowed reading range. Count valid readings before checking the threshold.
This is the same parsing pattern used in the Scanner lesson. The catch handles a conversion failure; it does not mean that every int is an acceptable reading. Keep format validation and the 0..100 domain check separate.
Reveal the explained lab solution
Main.java · Bounded reading-search solution
Predict the result, edit Main.java, then run your program.
Standard input · prefilled example
Select Run code to compile and execute this program.
The header enforces a six-line budget and checks input availability. Reading happens before validation, so every rejection consumes a line; continue then reaches slot++ automatically. The line count and slot have related but different roles: one reports actual input consumption, and the other controls the budget. Only accepted readings increment validReadings. The matching reading is counted before break, while the following 99 is never read. The final condition checks found first, so a match on the sixth line is reported as success rather than merely reaching the budget. As a consistency check, validReadings + skippedReadings must equal linesRead.
Test changes and boundaries
Edit the input box for each test. Reset restores the source and sample input. Check both the exit reason and the counts; a correct-looking match can still conceal a line-budget or counting error.
- Run the prefilled input: only four of the five supplied lines are read. The valid and skipped counts are both 2.
- Test 79, 80, and 81 individually. 79 ends without a match; 80 and 81 stop on their first line. Test 0 and 100 as valid range boundaries too.
- Try a blank line, text, 2147483648, -1, and 101 before 80. All five rejected lines consume budget, and the match on line six still wins the exit reason.
- Supply six low valid readings followed by 99. Only the first six may print; the exit reason must be read limit reached, not threshold reached.
- Clear the input for zero reads and input ended. Try 45 without a final newline for one accepted reading and input ended. In both cases print the summary once.
Common mistakes and how to diagnose them
The loop skips its intended first or last value
Trace the initial counter, the comparison, and the update separately. An array's final valid position is length - 1, so index < length is correct. A one-based numbered task may instead need <= its final task number.
The search ends after the first rejected value
Check whether break was used where continue was intended. break ends the current loop; continue skips the rest of just that iteration. Place the relevant validity check before accepted-work counters and calculations.
continue makes a while loop repeat the same value
Unlike a basic for header, a while has no automatic update stage. A manual update after continue is skipped. Consume input or advance state before taking a repeating path, or restructure the body so progress is unavoidable.
An enhanced-for assignment does not change the int array
The local primitive element variable holds a copied value. Assigning a different int to it does not write back to the array. Use an indexed assignment when you intend to modify a particular element.
The counter cannot be used after the loop
A variable declared in a for initializer is scoped to that loop. Keep it there when it is temporary; declare a separate result or count outside when later code needs a meaningful summary.
The wrong exit reason prints at the read limit
The matching value may occur on the last allowed line. Check the match flag before the budget condition. Also count malformed lines as consumed input if the budget is defined in lines rather than accepted readings.
Frequently asked questions
Does a for loop initialize its counter again on every iteration?
No. Its initializer runs once when the loop starts. The repeated sequence is condition, body, update, and then the next condition check.
Does continue skip the for update?
Not for an unlabelled continue targeting that basic for loop. Its update expressions run before the next condition check. A while has no equivalent update slot, so manual updates in its skipped body do not happen.
When should I use enhanced for?
When reading each value in order is enough and you do not need its index. Use a basic indexed loop for positions, selected strides, reverse traversal, or assignments to particular primitive array entries.
Does break stop every enclosing loop?
An unlabelled break exits the nearest enclosing loop or switch. Other enclosing loops may continue. return exits the current method instead, which also skips later method work such as a summary.
Why does the lab count invalid lines?
The budget is six input lines, not six valid readings. Reading a malformed or out-of-range value still consumes one of those lines. Valid and skipped counts partition the lines actually read.
Make every iteration and exit explainable
Basic for repeats a condition, body, and update after one initialization. Enhanced for visits values without a manual index. continue skips the rest of a targeted loop iteration, while break leaves the nearest enclosing loop or switch. Keep input consumption and result counting consistent with their definitions.
Before moving on, explain why 99 in the sample input is never processed, why a match on line six outranks the read-limit reason, and why a while continue needs its own progress strategy. Next: arrays and multidimensional arrays.
Can you trace what is processed, skipped, and stopped?
Answer all six questions and read the explanations. Results are temporary on this page and do not save course progress.
References and related learning
The scenarios, explanations, examples, and exercises are original SovranCode material. Official references support the Java 21 language rules.
- Java 21 specification: basic and enhanced for
- Java 21 specification: break
- Java 21 specification: continue
Review loop progress · Review parsing and validation · Review switch exits · Java course roadmap.
Last updated: