Java continue Statement
Java continue Statement
The continue statement skips the rest of the current loop iteration and moves directly to the next one. The loop does not exit — it keeps running. Only the remaining code in the current pass is skipped.
The distinction between continue and break is one of the most tested Java control flow questions, and the confusion is understandable — both appear inside loops, both change the normal execution path, and both are triggered by an if condition. What separates them is the outcome: break ends the loop, continue preserves it while skipping one pass.
What Is the Java continue Statement?
The continue statement transfers control to the update expression in a for loop, or directly to the condition check in a while or do-while loop, bypassing all remaining statements in the current iteration body.
Where break says "stop the loop entirely," continue says "skip this particular item and move to the next." This makes continue the natural fit for filtering logic — process everything that qualifies, skip everything that does not, without nesting the success path inside an if block.
Like break, continue has two forms:
- ›Unlabeled continue — skips the current iteration of the innermost enclosing loop
- ›Labeled continue — skips the current iteration of a specific outer loop identified by its label
Syntax
Unlabeled continue
1for (int index = 0; index < limit; index++) {
2 if (shouldSkip(index)) {
3 continue; // jump to index++ then re-check condition
4 }
5 // this code runs only when shouldSkip returns false
6}continue in while and do-while
1while (condition) {
2 if (skipCondition) {
3 continue; // jump directly to condition re-check
4 }
5 // body runs only when skipCondition is false
6}Labeled continue
1outerLoop:
2for (int outer = 0; outer < outerLimit; outer++) {
3 for (int inner = 0; inner < innerLimit; inner++) {
4 if (skipThisOuterIteration) {
5 continue outerLoop; // skips rest of outer body, advances outer counter
6 }
7 }
8}In a for loop, continue jumps to the update expression — i++ or i-- — before re-checking the condition. In a while or do-while loop, it jumps directly to the condition check. This timing difference matters when the update has side effects.
Beginner Examples
continue in a for Loop — Skipping Invalid Entries
The cleanest everyday use: process only the valid items, skip everything else without exiting the loop.
1public class OrderFilterDemo {
2
3 public static void main(String[] args) {
4
5 double[] orderAmounts = {250.0, -50.0, 780.0, 0.0, 1200.0, -30.0, 450.0};
6 double validTotal = 0.0;
7 int validCount = 0;
8
9 for (double amount : orderAmounts) {
10 // Skip invalid amounts — negative or zero orders are data errors
11 if (amount <= 0) {
12 System.out.println("Skipping invalid amount: Rs." + amount);
13 continue; // jumps to the next element in the array
14 }
15 validTotal += amount;
16 validCount++;
17 }
18
19 System.out.println("\nValid orders processed: " + validCount);
20 System.out.printf("Total valid revenue: Rs.%.2f%n", validTotal);
21 }
22}Output:
Skipping invalid amount: Rs.-50.0
Skipping invalid amount: Rs.0.0
Skipping invalid amount: Rs.-30.0
Valid orders processed: 4
Total valid revenue: Rs.2680.00
The alternative to continue here is wrapping the processing logic in an else block. With continue, the main logic stays at the same indentation level — easier to read, especially when the processing block is long. During code reviews, teams consistently prefer continue for filtering over deep nesting.
continue in a while Loop — Skipping Blank Lines
1import java.util.List;
2
3public class LogParserDemo {
4
5 public static void main(String[] args) {
6
7 List<String> logLines = List.of(
8 "INFO App started",
9 "",
10 "ERROR Null pointer at OrderService:142",
11 " ",
12 "WARN Memory usage at 87%",
13 "",
14 "INFO Request processed in 42ms"
15 );
16
17 int lineIndex = 0;
18 int errorCount = 0;
19
20 System.out.println("Non-empty log entries:");
21
22 while (lineIndex < logLines.size()) {
23 String line = logLines.get(lineIndex);
24 lineIndex++;
25
26 // Skip blank or whitespace-only lines
27 if (line.isBlank()) {
28 continue; // jump to condition check — lineIndex already incremented
29 }
30
31 System.out.println(" " + line);
32 if (line.startsWith("ERROR")) {
33 errorCount++;
34 }
35 }
36
37 System.out.println("\nErrors found: " + errorCount);
38 }
39}Output:
Non-empty log entries:
INFO App started
ERROR Null pointer at OrderService:142
WARN Memory usage at 87%
INFO Request processed in 42ms
Errors found: 1
lineIndex++ runs before continue — the increment is inside the loop body, not in the header. This means continue correctly advances the index before skipping the blank-line processing. In a for loop the update expression runs automatically after continue; in while any manual update must happen before continue is reached or the loop will either skip it or produce an infinite loop.
Labeled continue — Skipping an Outer Loop Iteration
1public class ScheduleFilterDemo {
2
3 public static void main(String[] args) {
4
5 String[] shifts = {"MORNING", "AFTERNOON", "NIGHT"};
6 String[] employees = {"Rahul", "Priya", "Arjun", "Deepa"};
7
8 // Simulate "NIGHT" shift having no available staff today
9 String unavailableShift = "NIGHT";
10
11 System.out.println("Schedule assignments:");
12
13 shiftLoop:
14 for (String shift : shifts) {
15 if (shift.equals(unavailableShift)) {
16 System.out.println(" " + shift + " shift: skipped — no staff available.");
17 continue shiftLoop; // skips all employee assignments for this shift
18 }
19
20 for (String employee : employees) {
21 System.out.println(" " + shift + " shift → " + employee);
22 }
23 }
24 }
25}Output:
Schedule assignments:
MORNING shift → Rahul
MORNING shift → Priya
MORNING shift → Arjun
MORNING shift → Deepa
AFTERNOON shift → Rahul
AFTERNOON shift → Priya
AFTERNOON shift → Arjun
AFTERNOON shift → Deepa
NIGHT shift: skipped — no staff available.
continue shiftLoop skips the entire inner employee loop for the NIGHT shift and moves directly to the next shift in the outer loop. Without the label, a plain continue inside the outer loop would skip only the current outer iteration — it cannot be placed inside the inner loop and still target the outer one.
How continue Works Internally
Execution Flow — for Loop
The diagram below shows precisely where continue sends execution in a for loop versus normal flow.
for (init; condition; update)
|
Check condition
|
condition is true
|
Execute body
|
continue reached?
|
+----------+----------+
| |
Yes No
| |
Jump to update Finish body
expression (i++) |
| Jump to update
Re-check condition expression
In a while loop, continue skips the update (there is no automatic one) and jumps straight to the condition check. This is why while loops with continue require the index increment to appear before the continue statement — if it comes after, the increment is skipped and the loop can hang.
continue vs break — Side-by-Side Behavior
1public class BreakVsContinueDemo {
2
3 public static void main(String[] args) {
4
5 System.out.println("--- continue: skips current iteration, loop continues ---");
6 for (int i = 1; i <= 5; i++) {
7 if (i == 3) continue;
8 System.out.print(i + " ");
9 }
10
11 System.out.println("\n--- break: exits the loop entirely ---");
12 for (int i = 1; i <= 5; i++) {
13 if (i == 3) break;
14 System.out.print(i + " ");
15 }
16 System.out.println();
17 }
18}Output:
--- continue: skips current iteration, loop continues ---
1 2 4 5
--- break: exits the loop entirely ---
1 2
With continue, element 3 is skipped but elements 4 and 5 still process. With break, the loop stops at element 3 — nothing after it runs. This side-by-side output is the clearest way to explain the behavioral difference in an interview.
Real-World Example — Batch Order Processing with Validation Skip
The Business Problem
You are building the order processing pipeline for an Indian quick-commerce platform — similar to what Swiggy Instamart or Blinkit runs for its warehouse fulfillment layer. Each order in a batch must pass three validation checks before it is dispatched to the fulfillment system. Orders that fail any validation are logged and skipped — they are not dispatched and not included in fulfillment counts. Valid orders proceed through the full pipeline.
This is the production continue pattern: validate first, skip on failure, process on success. Using if blocks to nest the success path would add indentation for every validation step. continue keeps the validation guards at the same level as the processing logic.
Implementation
1// File: OrderRecord.java
2
3public class OrderRecord {
4
5 private final String orderId;
6 private final String customerPhone;
7 private final double orderValue;
8 private final int itemCount;
9
10 public OrderRecord(String orderId, String customerPhone,
11 double orderValue, int itemCount) {
12 this.orderId = orderId;
13 this.customerPhone = customerPhone;
14 this.orderValue = orderValue;
15 this.itemCount = itemCount;
16 }
17
18 public String getOrderId() { return orderId; }
19 public String getCustomerPhone() { return customerPhone; }
20 public double getOrderValue() { return orderValue; }
21 public int getItemCount() { return itemCount; }
22}1// File: BatchProcessorConfig.java
2
3public final class BatchProcessorConfig {
4
5 public static final double MIN_ORDER_VALUE = 99.0;
6 public static final int MAX_ITEM_COUNT = 20;
7
8 private BatchProcessorConfig() {}
9}1// File: BatchOrderProcessor.java
2
3import java.util.List;
4
5public class BatchOrderProcessor {
6
7 public void processBatch(List<OrderRecord> orders) {
8
9 int dispatched = 0;
10 int skipped = 0;
11 double totalValue = 0.0;
12
13 System.out.println("=== Batch Processing Started ===\n");
14
15 for (OrderRecord order : orders) {
16
17 // Validation gate 1: phone number must be 10 digits
18 if (order.getCustomerPhone() == null
19 || order.getCustomerPhone().length() != 10) {
20 System.out.println("SKIPPED | " + order.getOrderId()
21 + " | Invalid phone number.");
22 skipped++;
23 continue; // skip dispatch — move to next order
24 }
25
26 // Validation gate 2: order value must meet minimum
27 if (order.getOrderValue() < BatchProcessorConfig.MIN_ORDER_VALUE) {
28 System.out.println("SKIPPED | " + order.getOrderId()
29 + " | Order value Rs." + order.getOrderValue()
30 + " below minimum Rs." + BatchProcessorConfig.MIN_ORDER_VALUE);
31 skipped++;
32 continue; // skip dispatch — move to next order
33 }
34
35 // Validation gate 3: item count must not exceed warehouse limit
36 if (order.getItemCount() > BatchProcessorConfig.MAX_ITEM_COUNT) {
37 System.out.println("SKIPPED | " + order.getOrderId()
38 + " | Item count " + order.getItemCount()
39 + " exceeds maximum " + BatchProcessorConfig.MAX_ITEM_COUNT);
40 skipped++;
41 continue; // skip dispatch — move to next order
42 }
43
44 // All validations passed — dispatch this order
45 System.out.println("DISPATCHED | " + order.getOrderId()
46 + " | Rs." + order.getOrderValue()
47 + " | " + order.getItemCount() + " items");
48 dispatched++;
49 totalValue += order.getOrderValue();
50 }
51
52 System.out.println("\n=== Batch Summary ===");
53 System.out.println("Dispatched : " + dispatched);
54 System.out.println("Skipped : " + skipped);
55 System.out.printf("Total value: Rs.%.2f%n", totalValue);
56 }
57}1// File: BatchDemo.java
2
3import java.util.List;
4
5public class BatchDemo {
6
7 public static void main(String[] args) {
8
9 List<OrderRecord> batch = List.of(
10 new OrderRecord("ORD-001", "9876543210", 450.0, 5),
11 new OrderRecord("ORD-002", "12345", 320.0, 3), // invalid phone
12 new OrderRecord("ORD-003", "8765432109", 75.0, 2), // below minimum
13 new OrderRecord("ORD-004", "7654321098", 890.0, 25), // too many items
14 new OrderRecord("ORD-005", "6543210987", 210.0, 8)
15 );
16
17 BatchOrderProcessor processor = new BatchOrderProcessor();
18 processor.processBatch(batch);
19 }
20}Output:
=== Batch Processing Started ===
DISPATCHED | ORD-001 | Rs.450.0 | 5 items
SKIPPED | ORD-002 | Invalid phone number.
SKIPPED | ORD-003 | Order value Rs.75.0 below minimum Rs.99.0
SKIPPED | ORD-004 | Item count 25 exceeds maximum 20
DISPATCHED | ORD-005 | Rs.210.0 | 8 items
=== Batch Summary ===
Dispatched : 2
Skipped : 3
Total value: Rs.660.00
Three validation guards, each followed by continue on failure. The dispatch logic at the bottom runs only when all three guards pass — flat, readable, and easy to extend with a fourth guard without adding another level of nesting. A mistake that appears often in fresher pull requests is writing these three guards as nested if blocks — the dispatch logic ends up at three levels of indentation for no logical reason.
The constants live in BatchProcessorConfig. When the minimum order value changes from Rs. 99 to Rs. 149, only the config file changes — not the processing loop.
Best Practices
Use continue to replace else blocks in filtering loops
When a loop processes elements that pass a filter and skips those that do not, continue on the failure condition keeps the success path flat. The equivalent else block nests the success logic unnecessarily.
1// Nested else — success logic at second indent level
2for (String item : items) {
3 if (isInvalid(item)) {
4 logInvalid(item);
5 } else {
6 process(item); // unnecessary nesting
7 record(item);
8 }
9}
10
11// continue — success logic stays flat
12for (String item : items) {
13 if (isInvalid(item)) {
14 logInvalid(item);
15 continue;
16 }
17 process(item);
18 record(item);
19}In while loops, always update the index before continue
In a for loop, the update expression runs automatically after continue. In a while loop, no such automatic update exists — if you use continue and the index update comes after it in the body, the index never increments, the condition never changes, and the loop hangs.
1int index = 0;
2while (index < items.size()) {
3 index++; // must come BEFORE continue to avoid infinite loop
4 if (shouldSkip(items.get(index - 1))) {
5 continue;
6 }
7 process(items.get(index - 1));
8}Use labeled continue sparingly — prefer method extraction
When logic requires continue outerLoop deep inside a nested structure, consider whether extracting the inner loop into a method and using return is clearer. return exits the method entirely, which has the same effect as continue outerLoop from the outer loop's perspective.
Common Mistakes
Mistake 1 — Placing the while Loop Index Update After continue
1public class InfiniteLoopMistakeDemo {
2
3 public static void main(String[] args) {
4
5 java.util.List<String> items = java.util.List.of("A", "", "B", "", "C");
6 int index = 0;
7
8 // This causes an infinite loop when an empty string is encountered
9 // because index++ never runs — continue skips it
10 while (index < items.size()) {
11 if (items.get(index).isEmpty()) {
12 continue; // index++ below is never reached — infinite loop
13 }
14 System.out.println(items.get(index));
15 index++; // this line is skipped when continue fires on an empty string
16 }
17 }
18}The index++ after continue is unreachable when continue fires. The while loop re-checks index < items.size() — but index is still 0 if the first item was empty. The fix is always to put the index update before the continue.
Mistake 2 — Confusing continue with break
1public class ConfusionDemo {
2
3 public static void main(String[] args) {
4
5 int[] values = {10, 20, 30, 40, 50};
6
7 System.out.println("With continue — skips 30, processes all others:");
8 for (int value : values) {
9 if (value == 30) continue;
10 System.out.print(value + " ");
11 }
12
13 System.out.println("\n\nWith break — stops at 30, never reaches 40 or 50:");
14 for (int value : values) {
15 if (value == 30) break;
16 System.out.print(value + " ");
17 }
18 System.out.println();
19 }
20}Output:
With continue — skips 30, processes all others:
10 20 40 50
With break — stops at 30, never reaches 40 or 50:
10 20
continue at 30 skips that element and continues with 40 and 50. break at 30 stops the loop — 40 and 50 are never seen. The confusion often happens because both appear inside an if inside a loop. The keyword itself is the entire difference.
Mistake 3 — Using continue in switch (It Does Not Apply)
1// continue is NOT valid inside a switch statement that is not inside a loop
2switch (status) {
3 case "PENDING":
4 // continue; // compile error if not inside a loop
5 break; // this is correct for switch
6 case "COMPLETED":
7 process();
8 break;
9}continue applies to loops, not to switch. If a switch is inside a loop, continue inside the switch applies to the enclosing loop — not to the switch itself. This is a nuance that appears in interview questions about control flow.
Mistake 4 — Unreachable Code After continue
1for (int i = 0; i < 5; i++) {
2 if (i % 2 == 0) {
3 continue;
4 System.out.println("Even: " + i); // never reached — compile warning
5 }
6 System.out.println("Odd: " + i);
7}Any statement placed after continue in the same block is unreachable and produces a compiler warning or error. Move the println before continue or remove it.
Interview Questions
Q1. What is the difference between break and continue in Java?
break exits the enclosing loop entirely — no further iterations occur after it fires. continue skips the rest of the current iteration's body and immediately moves to the next iteration — the loop continues running. Use break when the loop's purpose is complete. Use continue when the current element fails a filter but remaining elements should still be processed.
Q2. Where does continue transfer control in a for loop versus a while loop?
In a for loop, continue jumps to the update expression — i++ or equivalent — then re-checks the condition. In a while or do-while loop, continue jumps directly to the condition check, bypassing any index update that follows it in the body. This is why while loops using continue must place their index update before the continue statement, or the update is skipped and the loop can run indefinitely.
Q3. What is a labeled continue in Java?
A labeled continue skips the current iteration of the loop named by the label, not just the innermost enclosing loop. You place the label before an outer loop — outerLoop: — and write continue outerLoop; inside any inner loop to skip the rest of the outer loop's current body and advance to the outer loop's next iteration. This is useful when a condition encountered in an inner loop means the entire outer iteration should be abandoned.
Q4. Can continue be used inside a switch statement?
continue is not valid for switch itself — switch does not have iterations. However, if a switch statement is placed inside a loop, continue inside the switch applies to the enclosing loop, not to the switch. This causes the current loop iteration to skip and the next to begin. break inside a switch exits the switch; continue inside a switch (within a loop) exits the loop's current iteration. Knowing this distinction is tested in both service-based and product-based interviews.
Q5. How does continue help avoid deep nesting in loop bodies?
When a loop needs to filter elements before processing them, the alternative to continue is wrapping the processing logic in an else block or a deeply nested if. Each additional filter adds another nesting level. With continue, each filter becomes a guard at the top of the loop body — fail the guard and continue, otherwise process. The success path stays at the same indentation level regardless of how many guards are added, which is cleaner and easier to extend.
Q6. What happens if continue is placed inside a do-while loop?
In a do-while loop, continue jumps to the condition check at the bottom of the loop. The condition is evaluated, and if true, the body runs again from the top. The key difference from while is that the condition check in do-while is at the end — continue in a do-while always results in at least the condition being checked once more, whereas in a while loop it jumps to the same condition check at the top.
FAQs
What does the continue statement do in Java?
continue skips the rest of the current loop iteration and immediately moves to the next one. The loop does not exit — it keeps running with the next element or iteration. Only the remaining code in the current pass is skipped.
What is the difference between continue and break in Java?
break exits the enclosing loop entirely. continue skips only the current iteration and continues the loop. After break, no more iterations run. After continue, the loop proceeds normally with the next iteration.
Can continue be used in all loop types in Java?
Yes — continue works in for, while, and do-while loops. Its behavior is slightly different in each: in for it jumps to the update expression, in while and do-while it jumps to the condition check.
What is a labeled continue in Java?
A labeled continue skips the current iteration of a specific outer loop identified by its label. It is useful in nested loops when a condition inside the inner loop means the outer loop's current iteration should be abandoned entirely.
Does continue work inside a switch in Java?
continue is not valid for switch itself — switch has no iterations. If the switch is inside a loop, continue inside the switch applies to the enclosing loop, causing the current loop iteration to skip. break inside switch exits only the switch, not the loop.
When should I use continue instead of if-else?
Use continue when a loop processes elements that pass a filter and skips those that do not. Instead of wrapping the success path in an else block, place the skip condition with continue at the top and let the success path run flat. This reduces nesting and makes it easier to add new filters later.
Summary
The continue statement skips the current loop iteration and moves to the next — the loop itself keeps running. This single behavioral characteristic makes it the correct tool for filtering patterns: validate at the top, skip on failure with continue, process on success in the remaining body.
The most important behavioral detail to remember: in a for loop, continue jumps to the update expression before re-checking the condition. In a while loop, it jumps straight to the condition check — meaning any manual index update placed after continue in a while body is silently skipped, which causes an infinite loop. Always put while loop index updates before continue.
For interviews, know the difference from break by name and with a concrete output example, explain where continue transfers control in for versus while, and be ready to discuss whether continue inside a switch that is inside a loop applies to the switch or the loop. These three points cover the depth tested across both service-based recall questions and product-based design discussions.
What to Read Next
| Topic | Link |
|---|---|
| How the break statement exits loops and prevents switch fall-through | break Statement → |
| How the for loop uses continue to skip elements during iteration | for Loop → |
| How the while loop interacts with continue for runtime-driven filtering | while Loop → |
| How nested loops use labeled continue to skip outer iterations | Nested Loops → |
| How the return statement exits an entire method from inside a loop | return Statement → |