ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Control Flow
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 2.5

Control Flow

if, if-else, switch, for, enhanced for, while, do-while, break, continue and return — including switch expressions and pattern matching

13 min readStage 1 · Foundations14 interview questions
Prerequisites
2.3 Variables · 2.4 Operators
Covers
if · if-else · switch · for · Enhanced for · while · do-while · break · continue · return
Related
6.3 Polymorphism · 6.4 Inheritance Design (sealed types) · B1V3 Streams · Book 5 Vol IV (State, Strategy patterns)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

By default, statements run one after another. Control-flow statements change that order: they select which statements run (if, switch), repeat statements (for, enhanced for, while, do-while) and transfer control elsewhere (break, continue, return, and throw). Modern Java adds switch expressions and pattern matching, which turn much branching code into expressions that produce values and are checked for completeness by the compiler.

2Why It Exists

Every algorithm needs decisions and repetition. The newer forms exist because the classic forms had well-known failure modes: fall-through in switch, verbose casts after type checks, and missing cases that the compiler could not detect. Switch expressions and patterns address these directly.

3Core Concepts

if

if (condition) statement runs the statement only when the condition — which must be a boolean, never an integer — is true. Always use braces, even for one statement: it prevents the classic bug of adding a second line that appears to be inside the if but is not.

if-else

if … else chooses between two paths; else if chains test conditions in order and the first true condition wins, so order the conditions from most specific to least specific. An else binds to the nearest unmatched if (the "dangling else"), another reason to use braces.

An else-if chain: conditions are tested top to bottom
Figure 1 — An else-if chain: conditions are tested top to bottom

switch

switch selects a branch based on a value. Selector types are int and smaller integer types, their wrappers, char, String, enums and — since Java 21, with pattern matching — any reference type. There are two forms:

  • Colon form (case X:) — the classic statement. Execution falls through into the next case unless a break stops it.
  • Arrow form (case X ->) — no fall-through; each case runs exactly one expression, block or throw. Multiple labels can share a case: case SAT, SUN ->.

A switch can also be an expression that produces a value. Every possible input must be handled — the compiler checks exhaustiveness for enums and sealed types — and a block inside a case returns its value with yield.

Fall-through in the classic statement versus the arrow form of a switch expression
Figure 2 — Fall-through in the classic statement versus the arrow form of a switch expression

With pattern matching (final since Java 21), cases can match on type and shape: case Circle c ->, record patterns such as case Rectangle(double w, double h) ->, and guards with when: case Card c when c.amount() > 1000 ->. A switch with patterns can also handle case null explicitly; without it, a null selector throws NullPointerException.

for

for (init; condition; update) is the counting loop. The condition is tested before each iteration, so the body may run zero times. Any part may be empty; for (;;) is an infinite loop.

Enhanced for

for (Type item : source) iterates over arrays and any Iterable. It hides the index or iterator, which removes off-by-one errors, but it cannot modify the collection's structure: removing elements during iteration usually throws ConcurrentModificationException for standard collections. Use Iterator.remove() or removeIf instead.

while

while (condition) repeats while the condition is true, testing before each iteration. Use it when the number of iterations is not known in advance — reading until end of input, polling until a state changes.

do-while

do { … } while (condition); tests after the body, so the body always runs at least once. It fits retry loops and menus. Note the required semicolon.

for and while test before the body; do-while tests after it
Figure 3 — for and while test before the body; do-while tests after it

break

break leaves the innermost loop or switch immediately. With a label — break outer; — it leaves the labelled enclosing statement, which is the clean way to exit nested loops once a search succeeds.

continue

continue skips the rest of the current iteration and starts the next one; continue outer; continues the labelled outer loop. Used sparingly it simplifies filtering at the top of a loop body; used heavily it makes loops hard to follow.

return

return leaves the current method, with a value if the method is not void. finally blocks still run before the method actually returns. Early returns for guard conditions ("if invalid, return") usually make code flatter and clearer than deeply nested if blocks.

Where each jump statement transfers control
Figure 4 — Where each jump statement transfers control

4How It Works Internally

if and loops compile to conditional and unconditional jump bytecodes (ifeq, if_icmpge, goto). A switch on dense integer values compiles to a tableswitch (a direct jump table); sparse values to a lookupswitch. A switch on String switches on hashCode() and then checks equals. Enum switches use the ordinal. Pattern-matching switches compile to an invokedynamic call that selects the matching case at run time, and exhaustive switches over sealed types include a hidden default that throws MatchException if a new subtype appears without recompilation.

What a switch compiles to, by selector type
Figure 5 — What a switch compiles to, by selector type

Figure 5 summarises the four strategies. They explain two practical facts. First, the number of cases hardly affects the speed of a switch on integers, enums or strings, so a long switch is a readability problem, not a performance one. Second, the hidden branch of an exhaustive switch is a safety net for separate compilation: if a library adds an enum constant or a permitted subtype and the calling code is not recompiled, the switch fails loudly with MatchException instead of silently doing nothing. Loops have no special bytecode at all; a for, a while and a do-while that do the same work compile to almost the same jumps.

5APIs / Features / Syntax

FeatureSinceExample
Arrow labels, switch expressions, yieldJava 14int d = switch (m) { case FEB -> 28; default -> 30; };
Pattern matching for instanceofJava 16if (o instanceof String s)
Pattern matching for switch, guards (when), case nullJava 21case Card c when c.amount() > 1000 ->
Record patternsJava 21case Point(int x, int y) ->
Unnamed patterns _Java 22case Point(int x, _) ->
Primitive types in patternsPreview in Java 25case int i when i > 0 ->

6Practical Examples

Example 1 — Exhaustive switch over a sealed hierarchy

JAVAPattern matching with guards, record patterns and unnamed patterns
sealed interface Payment permits Card, Upi, BankTransfer {}
record Card(String last4, BigDecimal amount) implements Payment {}
record Upi(String vpa, BigDecimal amount) implements Payment {}
record BankTransfer(String iban, BigDecimal amount) implements Payment {}

BigDecimal fee(Payment p) {
    return switch (p) {
        case Card c when c.amount().compareTo(LIMIT) > 0
                                      -> c.amount().multiply(HIGH_RATE);
        case Card c                   -> c.amount().multiply(CARD_RATE);
        case Upi _                    -> BigDecimal.ZERO;
        case BankTransfer(_, var amt) -> FLAT_FEE.min(amt);
    };   // no default: the compiler knows all Payment types are covered
}

If a new Payment type is added to the permits list, every such switch stops compiling until the new case is handled — the compiler turns a forgotten case into a build error instead of a production bug.

Example 2 — Mini program: an order workflow driven by an exhaustive switch

Problem. An order moves through NEW, PAID, SHIPPED and DELIVERED, or is CANCELLED. Events arrive in any order, and invalid ones must be rejected without corrupting the state. The program combines most of this topic: a sealed event hierarchy, a switch expression with patterns and guards, an enhanced for, break, continue and return.

JAVAOrderFlow.java
import java.util.List;
 
public class OrderFlow {
    enum State { NEW, PAID, SHIPPED, DELIVERED, CANCELLED }
 
    sealed interface Event permits Pay, Ship, Deliver, Cancel {}
    record Pay(long paise) implements Event {}
    record Ship(String carrier) implements Event {}
    record Deliver() implements Event {}
    record Cancel(String reason) implements Event {}
 
    static State next(State s, Event e) {
        return switch (e) {                  // no default: all Events listed
            case Pay p when s == State.NEW && p.paise() > 0 -> State.PAID;
            case Ship sh when s == State.PAID -> State.SHIPPED;
            case Deliver d when s == State.SHIPPED -> State.DELIVERED;
            case Cancel c when s == State.NEW || s == State.PAID
                    -> State.CANCELLED;
            case Pay p -> s;                      // not allowed in this state:
            case Ship sh -> s;                    // the state stays as it is
            case Deliver d -> s;
            case Cancel c -> s;
        };
    }
 
    static State run(String order, List<Event> events) {
        State state = State.NEW;
        for (Event e : events) {
            if (state == State.DELIVERED || state == State.CANCELLED) {
                System.out.println(order + ": closed, ignoring the rest");
                break;                            // leave the loop early
            }
            State after = next(state, e);
            String name = e.getClass().getSimpleName();
            if (after == state) {
                System.out.println(order + ": " + name + " rejected in "
                        + state);
                continue;                         // skip to the next event
            }
            System.out.println(order + ": " + state + " -> " + after
                    + " (" + name + ")");
            state = after;
        }
        return state;
    }
 
    public static void main(String[] args) {
        run("A-17", List.of(new Pay(49_900), new Ship("BlueDart"),
                new Deliver(), new Cancel("late")));
        run("A-18", List.of(new Ship("BlueDart"), new Pay(0), new Pay(12_000),
                new Cancel("customer")));
    }
}
OUTPUT
A-17: NEW -> PAID (Pay)
A-17: PAID -> SHIPPED (Ship)
A-17: SHIPPED -> DELIVERED (Deliver)
A-17: closed, ignoring the rest
A-18: Ship rejected in NEW
A-18: Pay rejected in NEW
A-18: NEW -> PAID (Pay)
A-18: PAID -> CANCELLED (Cancel)

Why it behaves this way. next is one switch expression (Figure 6). Cases are tried from top to bottom, so a guarded case such as case Pay p when s == State.NEW && p.paise() > 0 wins only when its condition holds, and the unguarded case Pay p below it catches every other payment. Order A-18 shows both: shipping before payment and a payment of 0 are rejected, and the state stays NEW. There is no default, so a fifth event type added to permits makes next fail to compile until it is handled. In run, continue skips the state change for a rejected event and break leaves the loop once the order is closed, which is why A-17 ignores the late cancellation.

The order workflow of Example 2: states, events and the switch that decides
Figure 6 — The order workflow of Example 2: states, events and the switch that decides

Example 3 — Loops and removal

JAVAChoosing the right loop
for (int i = 0; i < orders.size(); i++) { … }      // index needed

for (Order o : orders) {                              // no index needed
    if (o.isCancelled()) orders.remove(o);   // ConcurrentModificationException
}

orders.removeIf(Order::isCancelled);                  // correct and clear

int attempts = 0;
boolean sent;
do {                                                  // at least one attempt
    sent = gateway.trySend(message);
    attempts++;
} while (!sent && attempts < 3);

Example 4 — A retry loop with a limit and back-off

Problem. Example 3 caps a retry loop at three attempts but retries immediately. Section 8 warns that immediate, unbounded retries can overload a service that is already struggling. This version waits longer before each retry, adds random jitter, and gives up after a fixed number of attempts.

JAVARetryLoop.java
import java.util.Random;
 
public class RetryLoop {
    interface Gateway { boolean trySend(String message); }
 
    static String send(Gateway g, String msg, int maxAttempts)
            throws InterruptedException {
        Random random = new Random(42);           // fixed seed: repeatable
        int delay = 100;                          // ms before the first retry
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            if (g.trySend(msg)) return msg + " sent on attempt " + attempt;
            if (attempt == maxAttempts) break;    // no wait after the last try
            int wait = delay / 2 + random.nextInt(delay / 2 + 1);   // jitter
            System.out.println("  attempt " + attempt + " failed, waiting "
                    + wait + " ms");
            Thread.sleep(wait / 10);              // shortened for the demo
            delay = Math.min(delay * 2, 2_000);   // exponential, capped
        }
        return msg + " NOT sent after " + maxAttempts + " attempts";
    }
 
    public static void main(String[] args) throws InterruptedException {
        int[] calls = {0};
        Gateway recovering = m -> ++calls[0] > 2; // fails twice, then works
        Gateway down = m -> false;                // an outage
        System.out.println(send(recovering, "order-17", 5));
        System.out.println(send(down, "order-18", 4));
    }
}
OUTPUT
  attempt 1 failed, waiting 76 ms
  attempt 2 failed, waiting 159 ms
order-17 sent on attempt 3
  attempt 1 failed, waiting 76 ms
  attempt 2 failed, waiting 159 ms
  attempt 3 failed, waiting 290 ms
order-18 NOT sent after 4 attempts

Why it behaves this way. The loop has two exits: return as soon as a send succeeds, and the loop condition once maxAttempts is reached; the break skips a pointless wait after the last attempt. The base delay doubles from 100 ms and is capped at 2 seconds, and each wait is a random value between half and all of it, so that thousands of clients that failed together do not retry at the same moment. The fixed seed makes the waits repeatable for the book; production code uses an unseeded random source, or a library such as Resilience4j, which adds a circuit breaker (Book 7).

JAVAExiting nested loops
Seat found = null;
search:
for (Row row : theatre.rows()) {
    for (Seat seat : row.seats()) {
        if (seat.isFree() && seat.isAisle()) {
            found = seat;
            break search;          // leaves both loops
        }
    }
}

Example 6 — Fall-through: a feature, a bug and the fix

Problem. In a colon-form switch, execution continues into the next case unless break stops it. Sometimes that is intended, as when higher plans include the features of lower ones; often it is an accident. The program has one of each, and the arrow form that cannot fall through.

JAVAFallThrough.java
import java.util.ArrayList;
import java.util.List;
 
public class FallThrough {
    enum Plan { FREE, PRO, ENTERPRISE }
 
    @SuppressWarnings("fallthrough")
    static List<String> features(Plan p) {        // fall-through on purpose
        List<String> f = new ArrayList<>();
        switch (p) {
            case ENTERPRISE: f.add("sso");
            case PRO:        f.add("reports");
            case FREE:       f.add("orders");
        }
        return f;
    }
 
    static String supportOld(Plan p) {            // fall-through by accident
        String s = "community";
        switch (p) {
            case PRO:        s = "email";         // break missing
            case ENTERPRISE: s = "phone"; break;
            default:         break;
        }
        return s;
    }
 
    static String support(Plan p) {               // arrow form: no fall-through
        return switch (p) {
            case FREE -> "community";
            case PRO -> "email";
            case ENTERPRISE -> "phone";
        };
    }
 
    public static void main(String[] args) {
        for (Plan p : Plan.values())
            System.out.printf("%-10s %-24s %-9s %s%n",
                    p, features(p), supportOld(p), support(p));
    }
}
OUTPUT
FREE       [orders]                 community community
PRO        [reports, orders]        phone     email
ENTERPRISE [sso, reports, orders]   phone     phone

Why it behaves this way. features falls through on purpose: ENTERPRISE starts at the first case and collects all three features. supportOld has the same structure by accident: for PRO it sets "email" and then falls into the ENTERPRISE case, so PRO customers are promised phone support. The arrow form in support runs exactly one case and, as a switch expression, must cover every constant. javac warns about the accidental case with -Xlint:fallthrough ("possible fall-through into case"); the @SuppressWarnings("fallthrough") on features documents that its fall-through is intended.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Missing break in a colon-form switchSilent fall-through into the next caseUse arrow form or switch expressions
Removing from a collection inside enhanced forConcurrentModificationExceptionremoveIf, or an explicit Iterator
Comparing strings with == in conditionsBranch taken or skipped at randomequals, or switch on String
Floating-point loop counters (for (double d = 0; d != 1; d += 0.1))Infinite loop: 0.1 is not exactUse integer counters
Deeply nested if/elseHard to read and testGuard clauses with early return; polymorphism
Switch on a type with a default branchNew subtypes silently hit defaultSealed types with exhaustive switch, no default
Switching on a possibly null valueNullPointerExceptioncase null, or check before switching
return or throw inside finallyDiscards the exception or the return value of the try blockNever leave finally abruptly; use try-with-resources for clean-up (Q10)
Off-by-one loop bounds: i <= array.lengthArrayIndexOutOfBoundsException on the last iterationi < length, or an enhanced for when no index is needed
Retry loops without a limit, delay or jitterTurn a short outage into an overload of the downstream serviceCap the attempts, back off exponentially with jitter (Example 4)

8Performance & Production Considerations

  • The JIT optimises loops heavily — unrolling, removing bounds checks, vectorising simple numeric loops — so clear loops usually perform as well as "clever" ones.
  • A switch on dense integer or enum values is a jump table and costs the same regardless of the number of cases.
  • Unbounded retry loops (while (!sent)) without a limit or back-off can overload downstream systems during an outage; always cap attempts and add delay (Book 7 resilience).

9Architecture & Design Considerations

Branching on type is a design decision. Classic object-oriented design replaces if (x instanceof A) … else if (x instanceof B) with polymorphism: each subtype implements the behaviour (6.3, and the Strategy and State patterns in Book 5). Modern Java adds a second option — sealed types with exhaustive pattern matching — often called data-oriented programming.

ApproachBest whenAdding a new typeAdding a new operation
Polymorphism (method per subtype)The set of operations is stable; types growEasy: one new classHard: touch every class
Sealed types + switch patternsThe set of types is stable; operations growCompiler flags every switch to updateEasy: one new switch

10Interview Questions & Answers

Q1L1 · BasicConcept

What is the difference between while and do-while?

while tests the condition before each iteration, so the body can run zero times. do-while tests after the body, so the body always runs at least once. Use while when the body may not be needed at all, such as reading until end of input, and do-while when it must run once before the test makes sense, such as a first attempt or a menu.

Q2L1 · BasicConcept

What does break do inside a switch and inside a loop?

It leaves the innermost enclosing switch or loop immediately. In a colon-form switch, it is what prevents fall-through into the next case. A labelled break leaves an outer statement instead, and continue only ends the current iteration.

Q3L2 · IntermediateConcept

What is the difference between a switch statement and a switch expression?

A statement performs actions and may fall through between colon-form cases. An expression produces a value, uses arrow cases without fall-through or yield in block cases, and must be exhaustive — every possible input must be handled, which the compiler checks for enums and sealed types.

Q4L2 · IntermediateInternals

Why can you not remove elements from a list inside an enhanced for loop?

The enhanced for uses an iterator. Standard collections detect structural changes made outside that iterator and throw ConcurrentModificationException on the next step. Use Iterator.remove() or Collection.removeIf.

Q5L3 · Senior EngineerConcept

How do pattern matching and guards change switch?

Cases can match on type and structure — case Card c, case Point(int x, int y) — binding variables without explicit casts, and when adds conditions to a case. Combined with sealed types, the compiler verifies that all subtypes are handled, and case null can be handled explicitly.

Q6L3 · Senior EngineerDesign

Why should an exhaustive switch over a sealed interface usually have no default branch?

Without a default, adding a new permitted subtype causes every switch that does not handle it to fail compilation, pointing to exactly the code that must change. A default branch silently absorbs the new type and turns a compile-time error into a runtime behaviour bug.

Q7L3 · Senior EngineerScenario

A retry loop brought down a downstream service during an incident. What was wrong with it?

It likely retried immediately and without limit — while (!success) — multiplying load on a service that was already struggling. Retry loops need a maximum number of attempts, exponential back-off with jitter, and ideally a circuit breaker, so that failures reduce load instead of amplifying it.

Q8L4 · Technical ArchitectTrade-off

When would you choose sealed types with pattern matching over polymorphism?

When the set of types is closed and stable but operations over them grow — for example payment methods or domain events processed by many services. Exhaustive switches give compile-time guarantees that each operation handles every type. When new types are added frequently, or by other teams as plugins, polymorphism keeps each type's behaviour with the type and avoids touching every switch.

Q9L2 · IntermediateCode

What does this program print?

JAVASwitchQuiz.java
public class SwitchQuiz {
    public static void main(String[] args) {
        int level = 2;
        switch (level) {
            case 1:  System.out.print("one ");
            case 2:  System.out.print("two ");
            case 3:  System.out.println("three");
                     break;
            default: System.out.println("other");
        }
    }
}

It prints two three. The colon form jumps to case 2 and then falls through into case 3, because only break stops it; the break there prevents the default from running too. With arrow labels, case 2 -> ..., only "two" would be printed. javac reports both fall-throughs as warnings when compiled with -Xlint:fallthrough.

Q10L3 · Senior EngineerCode

What does this program print?

JAVAFinallyQuiz.java
public class FinallyQuiz {
    static int first() {
        try { return 1; }
        finally { System.out.println("finally runs"); }
    }
 
    @SuppressWarnings("finally")
    static int second() {
        try { throw new IllegalStateException("lost"); }
        finally { return 2; }                 // discards the exception
    }
 
    public static void main(String[] args) {
        System.out.println(first());
        System.out.println(second());
    }
}

It prints finally runs, then 1, then 2. In first, the return value 1 is computed and saved, then the finally block runs, and only then does the method return. In second, the return 2 in finally replaces the pending exception: the IllegalStateException disappears without a trace. That is why returning or throwing from finally is a defect, and why javac has a -Xlint:finally warning for it.

Q11L3 · Senior EngineerInternals

How does javac compile a switch on a String?

In two steps. First it switches on hashCode() of the selector with a lookupswitch, because hash values are sparse; within the matching hash it calls equals to rule out a collision, and sets a temporary index. A second switch on that index, usually a tableswitch, then runs the case body (Figure 5). The result is fast regardless of the number of cases, it throws NullPointerException for a null selector unless there is a case null, and it depends on String.hashCode being specified, which it is.

Q12L3 · Senior EngineerTricky

What does this program print, and why is there no ConcurrentModificationException?

JAVARemovalQuiz.java
import java.util.ArrayList;
import java.util.List;
 
public class RemovalQuiz {
    public static void main(String[] args) {
        var names = new ArrayList<>(List.of("asha", "ravi", "meera"));
        for (String n : names) {
            if (n.equals("ravi")) names.remove(n);
        }
        System.out.println(names);
    }
}

It prints [asha, meera] without an exception. The iterator checks for concurrent modification in next(), not in hasNext(). Removing "ravi", the second-to-last element, shrinks the list to two elements while the iterator's cursor is already 2, so hasNext() returns false and the loop ends; "meera" is never visited at all. With any other element the next next() call throws. The bug is therefore data-dependent, which is a strong reason to use removeIf or Iterator.remove.

Q13L4 · Technical ArchitectDesign

A pricing service has a 400-line if-else chain of discount rules that changes every month. How would you restructure it?

First separate the decision data from the code: most such chains are a table of conditions and discounts, which can become a list of rule objects, or configuration, evaluated in order with the first match winning, exactly like an else-if chain. Each rule then gets its own unit test, and new rules are added without touching the others. Where the branches depend on the kind of customer or order, a sealed hierarchy with an exhaustive switch, or a Strategy per kind, makes the structure explicit. If business users change the rules weekly, a rules engine or a feature-flag service may be justified, at the cost of a new runtime dependency and less compile-time checking.

Q14L5 · Solution ArchitectTrade-off

Across a large codebase, should expected failures such as "insufficient funds" be exceptions or return values?

Exceptions are idiomatic in Java, keep the normal path clean and carry stack traces, but they are invisible in method signatures when unchecked, expensive when thrown often, and easy to catch too broadly. A sealed result type, for example sealed interface PaymentResult permits Approved, Declined, makes every outcome part of the signature, and an exhaustive switch forces callers to handle each one. A good split is result types for expected business outcomes that callers must decide on, exceptions for programming errors and infrastructure failures, and a clear mapping of both to HTTP status codes or error events at the service boundary.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Conditions must be boolean; use braces everywhere.
  • Prefer arrow-form switches and switch expressions: no fall-through and compiler-checked exhaustiveness.
  • Pattern matching, record patterns and guards remove casts and make type-based branching safe.
  • Use the loop that states the intent; never modify a collection inside enhanced for.
  • break, continue, labelled break and return transfer control; cap every retry loop.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.