skip to content

Control Flow

Branching with if and switch, looping with for, while and do-while, jumping with break and continue, and the compiler's unreachable-code analysis. Modern switch expressions and pattern matching make this a livelier area than it used to be.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 1 of 2

What do the break and continue statements do inside a loop in Java?

level: juniorimportance: must knowfreq 75%

answer

  1. break = leave the loop
  2. continue = skip to next iteration
  3. for: continue -> update then condition
  4. while: continue -> condition directly (increment trap)
  5. innermost loop only

basics

~10 s

break stops the loop entirely and jumps to the code right after it. continue skips the rest of the current iteration and goes straight to the next one (re-checking the loop condition).

solid answer

~40 s

Both control the flow of a loop. break terminates the nearest enclosing loop (or switch) immediately and continues execution after that loop. continue ends only the current iteration: in a for loop it jumps to the update expression then re-tests the condition; in a while/do-while it jumps straight back to the condition test. Neither affects code outside the loop other than where execution resumes. A common use is break to stop searching once you've found a match, and continue to skip invalid or irrelevant items while still processing the rest. Without a label, both act only on the single innermost loop that contains them.

go deeper

for a junior

Can state that break leaves the loop and continue skips one iteration, and read simple examples correctly.

for a middle

Explains the for-vs-while difference (where continue jumps) and the while increment-trap that causes infinite loops.

for a senior

Discusses readability trade-offs, prefers guard-clause continue over deep nesting, and knows break also stops switch fall-through.

for a principal

Frames break/continue as structured-programming jump statements, weighs them against early return / extracted methods, and sets team conventions for loop control clarity.

## What a loop is A *loop* repeats a block of code. Java has `for`, `while`, `do-while`, and the enhanced for (`for-each`). Each loop runs *iterations* until some condition stops it. Sometimes you want to leave a loop early, or skip part of one pass — that's what `break` and `continue` are for. They are *jump statements*: they move execution to a different place instead of running the next line in sequence. ## break `break;` immediately ends the **nearest enclosing loop** and resumes at the first statement *after* that loop. Nothing left in the loop body runs, and the loop condition is not checked again. ```java for (int i = 0; i < 10; i++) { if (i == 3) break; // leaves the loop System.out.println(i); // prints 0, 1, 2 } // execution continues here ``` `break` is also used in `switch` statements to stop fall-through; that is a separate use of the same keyword. ## continue `continue;` ends only the **current iteration** and moves on to the next one. The rest of the loop body below `continue` is skipped, but the loop itself keeps going. Where it jumps depends on the loop type: - In a **for** loop it jumps to the *update* part (e.g. `i++`), then re-tests the condition. - In a **while** / **do-while** loop it jumps straight to the *condition* test. ```java for (int i = 0; i < 5; i++) { if (i % 2 == 0) continue; // skip even numbers System.out.println(i); // prints 1, 3 } ``` ## A subtle for-vs-while trap Because `continue` in a `while` loop skips straight to the condition, any increment written *after* the `continue` is never reached — an easy way to create an infinite loop: ```java int i = 0; while (i < 5) { if (i == 2) continue; // BUG: i never advances, loops forever i++; } ``` A `for` loop avoids this because the update expression always runs after `continue`. ## Scope: innermost loop only Unlabeled `break`/`continue` affect only the single loop directly containing them. With nested loops, a plain `break` exits just the inner loop — the outer loop keeps running. To affect an outer loop you need a *label* (covered separately). ## Summary - `break` = exit the whole loop now. - `continue` = skip to the next iteration now. - Both act on the innermost loop unless labeled.

  • In a for loop, does continue skip the i++ update expression?
    No. In a for loop continue jumps to the update part (i++) and then re-evaluates the condition, so the update still runs.
  • Can break be used outside a loop?
    Yes, in a switch statement to prevent fall-through. Using break with no enclosing loop or switch is a compile error.

saying these in an interview costs you the question

  • Saying continue exits the loop (it only skips one iteration)
  • Saying break ends the program or method (it ends the loop)
  • Forgetting that continue in a while loop can cause an infinite loop if the increment sits below it
  • Thinking unlabeled break exits all nested loops

context

open as a page

What is the enhanced for-each loop in Java and what is its syntax?

level: juniorimportance: must knowfreq 70%

basics

~10 s

It is a shorter loop for going through every element of an array or collection without a counter. You write 'for (Type item : collection)' and 'item' takes each value in turn.

open as a page

What are the three parts of a Java for loop, and in what order do they execute?

level: juniorimportance: must knowfreq 85%

basics

~10 s

A for loop has three parts in parentheses, separated by semicolons: initialization, condition, and update. Init runs once first; then each pass checks the condition, runs the body, then runs the update.

open as a page

What is the if statement in Java and how does the optional else clause work?

level: juniorimportance: must knowfreq 70%

basics

~10 s

An if statement runs a block of code only when its condition is true. An optional else block runs when the condition is false. The condition must be a boolean.

open as a page

How do else-if chains work in Java, and how does ordering affect which branch runs?

level: juniorimportance: must knowfreq 60%

basics

~10 s

An else-if chain tests conditions in order from top to bottom. The first condition that is true runs its block, and the rest are skipped. An optional final else catches everything else.

open as a page

What is a switch expression in Java, and how does the arrow (case ->) form differ from the traditional switch statement?

level: juniorimportance: must knowfreq 70%

basics

~10 s

A switch expression produces a value you can assign to a variable. The arrow form 'case X -> result;' runs only the matching branch with no fall-through, so you don't need break statements.

open as a page

What are type patterns in a switch, and how do they change what a switch can do compared to a traditional switch?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A type pattern in a switch case checks whether the value is of a given type and, if so, binds it to a new variable in one step. This lets a switch branch on the runtime type of an object, not just on constants like ints, enums, or strings.

open as a page

What is the traditional switch statement in Java, and how does control flow move through its cases?

level: juniorimportance: must knowfreq 70%

basics

~20 s

switch picks a branch by comparing one value against case labels. It jumps to the matching case and keeps running downward into later cases until it hits a break (or the end). default runs when nothing matches.

open as a page

What is unreachable code in Java, and what does the compiler do when it finds it?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Unreachable code is a statement that can never possibly run, such as a line written right after a return. Java treats this as a compile error, so the program will not build until you remove or fix it.

open as a page

What causes an infinite while loop and how do you ensure a loop terminates?

level: juniorimportance: must knowfreq 60%

basics

~20 s

A loop runs forever when its condition never becomes false. To make it terminate, the body must change something that the condition checks (like incrementing a counter) so the condition eventually turns false, or use break.

open as a page

What is the difference between a while loop and a do-while loop in Java?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A while loop checks the condition before running its body, so it may run zero times. A do-while loop runs the body once first, then checks the condition, so it always runs at least once.

open as a page

What happens if you remove or add elements to a collection while iterating it with a for-each loop, and how do you remove safely?

level: middleimportance: must knowfreq 75%

basics

~10 s

Changing the collection's size during a for-each usually throws a ConcurrentModificationException. To remove items safely, use an explicit Iterator and call its remove(), or use collection.removeIf(...).

open as a page

When and how do you use 'yield' in a switch expression?

level: middleimportance: must knowfreq 60%

basics

~10 s

Use 'yield' to return a value from a switch branch that is a block ({ ... }) and needs more than one statement. Single-expression arrow branches don't need it; they return their value directly.

open as a page

What is a guarded pattern (the `when` clause) in a switch, and how does it interact with case ordering and exhaustiveness?

level: middleimportance: must knowfreq 60%

basics

~20 s

A guarded pattern adds a boolean condition to a case using when, e.g. case Integer i when i > 0. The case matches only if the value fits the pattern AND the condition is true. If the guard is false, the switch keeps trying later cases.

open as a page

Explain fall-through in a traditional switch: when is it a deliberate tool and when is it a bug, and how do you guard against the bug?

level: middleimportance: must knowfreq 60%

basics

~20 s

Fall-through means after a case runs, execution keeps going into the next case unless you write break. It is deliberate when several labels share one body, but a forgotten break is a common bug. Always add break, or stack empty labels on purpose.

open as a page

What does exhaustiveness mean for a switch expression, and how does the compiler enforce it?

level: seniorimportance: must knowfreq 58%

basics

~10 s

A switch expression must cover every possible input value. You either add a 'default' branch or list all values (e.g. every enum constant). If you don't, it won't compile.

open as a page

When should you choose a for loop over a while loop, and why?

level: juniorimportance: should knowfreq 60%

basics

~20 s

Use a for loop when you know the number of repetitions or are counting over a range, because it keeps the counter setup, test, and update together. Use while when you just loop until some condition changes.

open as a page

How do labeled break and labeled continue work in Java, and when would you use them?

level: middleimportance: should knowfreq 50%

basics

~20 s

You put a name (a label) followed by a colon before a loop, like outer:. Then break outer; exits that labeled loop completely, and continue outer; jumps to the next iteration of that labeled loop. This lets you control an outer loop from inside an inner one.

open as a page

Precisely where does control transfer for break and continue in for, while, and do-while loops, including the for loop's update expression?

level: middleimportance: should knowfreq 45%

basics

~20 s

break sends control to right after the loop in all loop types. continue goes to the loop's condition check, but in a for loop it runs the update part (like i++) first. So a for loop's update always runs on continue; a while/do-while jumps straight to the condition.

open as a page

With nested loops in Java, which loop does an unlabeled break or continue affect, and why does that matter?

level: middleimportance: should knowfreq 55%

basics

~10 s

An unlabeled break or continue only affects the innermost loop that directly contains it. The outer loop keeps running. So a break inside an inner loop just ends that inner loop, not both.

open as a page

How does the for-each loop iterate over an array versus an Iterable, and what does the compiler generate for each?

level: middleimportance: should knowfreq 55%

basics

~10 s

For an array the compiler turns it into an index-based loop using array.length. For a collection it calls iterator() and uses hasNext()/next(). The source code looks the same, but the generated code differs.

open as a page

How can a Java for loop initialize or update more than one variable, and what separator is used?

level: middleimportance: should knowfreq 55%

basics

~20 s

You can list several expressions in the init or update clause separated by commas, like for (int i = 0, j = 10; i < j; i++, j--). The comma lets one loop track two counters at once.

open as a page

What does for(;;) do in Java, and how do you exit such a loop safely?

level: middleimportance: should knowfreq 50%

basics

~10 s

for(;;) is an infinite loop: with all three clauses empty, there is no condition so it never stops on its own. You leave it with break, return, or by throwing an exception.

open as a page

What is the dangling-else problem, and how does Java resolve which if an else binds to?

level: middleimportance: should knowfreq 45%

basics

~10 s

When an else could attach to more than one nested if, Java's rule is that else binds to the nearest unmatched if above it. Use braces to force the binding you actually want.

open as a page

How do short-circuit operators (&&, ||) behave inside if conditions, and why does it matter?

level: middleimportance: should knowfreq 50%

basics

~20 s

&& and || stop evaluating as soon as the result is known: && stops at the first false, || stops at the first true. This lets you safely guard later checks, like checking for null before using a value.

open as a page

How does a switch expression differ from a switch statement, and when would you choose each?

level: middleimportance: should knowfreq 50%

basics

~10 s

A switch statement does an action and returns nothing; a switch expression computes and returns a value. Use the expression to assign or return a result; use the statement for pure side effects.

open as a page

How does a pattern switch handle a null selector, and what does `case null` (and `case null, default`) do?

level: middleimportance: should knowfreq 55%

basics

~20 s

By default a switch throws NullPointerException if the value is null. To handle null safely you add case null, which runs only when the value is null. You can also write case null, default to send null to the default branch.

open as a page

Which types are allowed as the selector (and case labels) of a traditional Java switch, and which are not?

level: middleimportance: should knowfreq 55%

basics

~10 s

You can switch on int and the smaller whole-number types byte, short, char (and their wrapper classes), on enum constants, and on String. You cannot switch on long, float, double, boolean, or arbitrary objects.

open as a page

How does an infinite loop like 'while (true)' affect reachability of the code that follows it?

level: middleimportance: should knowfreq 40%

basics

~10 s

With 'while (true)' and no break, the loop never ends, so any statement written after it can never run. The compiler treats that following code as unreachable and reports a compile error.

open as a page

Why does 'while (false) { x(); }' fail to compile but 'if (false) { x(); }' compiles fine?

level: middleimportance: should knowfreq 48%

basics

~20 s

The body of 'while (false)' can never run, so Java flags it as unreachable code — a compile error. Java deliberately exempts 'if (false)' from this rule so it can be used to switch code on and off, like a conditional-compilation flag.

open as a page

showing 1–30 of 44