December Code

Java loops and control flow interview questions, with answers

Control-flow questions in Java are short and exact: a switch without a break, a loop with a label, a condition that never becomes false. They test whether you can run code in your head the way the JVM does, one statement at a time, including the parts that are easy to skim — which cases a switch falls into, where a break jumps to, and what a for-each loop hides. Every answer below comes with code, and every output shown was produced by compiling and running it.

The questions start with switch, old and new, then cover loops, the jumps out of them, and the conditional operator. Then take the free Java diagnostic — ten questions across every Java topic in the bank — to see which of these you can explain but not yet predict.

The questions, with answers

  1. 1.Why does a Java switch fall through, and how do you stop it?

    In short: In a classic switch, execution starts at the matching case and runs every case below it until a break or the end, so each case needs its own break; arrow-form cases never fall through.

    A case label is only an entry point, not a boundary. Once the switch jumps to the matching label, statements keep executing through the labels below it, which is the behaviour this page's sample asks about. Forgetting a break is the classic bug; deliberate fall-through is legal for grouping cases, as below, where 6 and 7 share one branch. default runs when no case matches, can appear anywhere, and falls through like any other label if it is not last. Since Java 14, the arrow form, case X ->, removes the problem entirely: each arrow case runs only its own statement or block. A switch on a String compares with equals(), and switching on a null reference throws NullPointerException unless the switch has a case null, allowed since Java 21.

    int day = 6;
    String kind;
    switch (day) {
        case 6:
        case 7:
            kind = "weekend";
            break;
        default:
            kind = "weekday";
    }
    System.out.println(kind);
    // weekend
  2. 2.What is a switch expression in Java, and how is it different from a switch statement?

    In short: A switch expression, standard since Java 14, produces a value: its arrow cases never fall through, and the compiler requires it to cover every possible input.

    Written with arrows, a switch expression maps each case to a value, so it can sit on the right of an assignment or after return. Several labels can share a case, as in case SAT, SUN -> 0, and a case that needs statements uses a block that hands back its value with yield, as below. The compiler checks exhaustiveness: over an enum, listing every constant is enough, while for an int or a String a default is required, and adding a constant to an enum makes every switch expression that does not handle it fail to compile, instead of silently missing it. Arrow cases also work in ordinary switch statements, where they simply remove fall-through. Interviewers ask this to see whether your Java is current.

    enum Day { MON, SAT, SUN }
    
    static int hours(Day d) {
        return switch (d) {
            case SAT, SUN -> 0;
            case MON -> {
                int h = 8;
                yield h + 1;
            }
        };
    }
    
    int h = hours(Day.MON);
    System.out.println(h);
    // 9
  3. 3.Which types can a Java switch work on?

    In short: A classic switch accepts char, byte, short, int, their wrapper classes, String and enums — not long, float, double or boolean — and Java 21 pattern matching extends it to any reference type.

    The classic limits come from how switch compiles: case labels are compile-time constants turned into a jump over int values, so long and the floating-point types were never allowed, and boolean has if instead. Strings arrived in Java 7, implemented with hashCode() and then equals(), and enums switch on their constants. Every case label must be a constant, so a variable in a label is a compile error unless it is a final variable initialised with a constant expression. Java 21's pattern matching lets a switch test types instead, as in case Integer i when i > 0 ->, which replaces the chains of instanceof checks older code used. Interviewers ask about long to check that you know the classic limits.

    String cmd = "stop";
    int code = switch (cmd) {
        case "go" -> 1;
        case "stop" -> 2;
        default -> 0;
    };
    System.out.println(code);
    // 2
  4. 4.How do labeled break and continue work in Java?

    In short: A label names an enclosing loop, so break with the label exits that loop entirely and continue with the label jumps to its next iteration, even from inside a nested loop.

    Unlabeled break and continue affect only the innermost loop, or the innermost switch in the case of break. When you need to leave two loops at once, as when a search over a grid finds its target, label the outer loop and break with the label, as below. continue with a label abandons the rest of the inner loop and moves the outer loop on to its next iteration. Java has no goto, and a label can only be used from inside the statement it labels. Some teams avoid labels by moving the nested loops into a method and returning from it; interviewers mainly want to see that you know exactly where each form sends control.

    int[][] g = {{1, 2}, {3, 4}};
    int found = -1;
    search:
    for (int[] row : g)
        for (int v : row)
            if (v > 2) {
                found = v;
                break search;
            }
    System.out.println(found);
    // 3
  5. 5.What is the difference between while and do-while in Java?

    In short: while checks its condition before each pass, so its body may never run, while do-while checks after each pass, so its body always runs at least once.

    The choice follows from where the test belongs. A while loop suits reading until input runs out, where there may be nothing to read at all. A do-while suits a menu or a retry prompt that must happen once before there is anything to test, and it needs a semicolon after its condition. Below, the while body never runs because 10 < 5 is false at the start, but the do-while body runs once anyway. Every loop needs something in its body that eventually makes the condition false; a loop that steps a double by 0.1 and tests != 1.0 never ends, because of rounding, so loop conditions on doubles use < or <=. All three loops can be rewritten as one another; pick the one whose shape matches the problem.

    int n = 10;
    while (n < 5) n++;
    System.out.println(n);
    // 10
    do n++; while (n < 5);
    System.out.println(n);
    // 11
  6. 6.What can't a for-each loop do in Java?

    In short: It gives no index, cannot replace or remove elements of what it walks over, and only moves forward; for any of those, use an indexed loop, an Iterator or removeIf.

    for (T x : items) is shorthand for an Iterator, or an index for arrays, that the loop hides from you. Assigning to x changes only the loop variable, never the element in the array or list, a common surprise shown below. Removing from a list inside the loop usually makes its hidden iterator throw ConcurrentModificationException on the next step. Use Iterator.remove() or removeIf with a condition to delete while iterating, use an indexed loop when you need the position or want to write elements back, and loop backwards over the indexes when removing by position. For-each works on arrays and on anything that implements Iterable, including your own classes.

    int[] a = {1, 2, 3};
    for (int x : a) x *= 10;
    System.out.println(a[0]);
    // 1
    int n = a.length;
    for (int i = 0; i < n; i++)
        a[i] *= 10;
    System.out.println(a[0]);
    // 10
  7. 7.What type does the ternary operator produce in Java?

    In short: cond ? a : b evaluates only one of a and b, but its type is worked out from both branches, so mixing an int with a double gives a double and a boxed null can be unboxed.

    The conditional operator is an expression, so unlike an if statement it has a value and a type. When both branches are numeric, Java applies numeric promotion across them even though only one is evaluated: t ? 1 : 2.0 has type double, so it produces 1.0, as below. When one branch is a boxed type such as Integer and the other a primitive int, the result type is int, so a null Integer in the chosen branch is unboxed and throws NullPointerException, even when the result is assigned back to an Integer. Keep both branches the same type, or cast one explicitly, to avoid both surprises. Nesting ternaries is legal but hard to read; a switch expression usually says the same thing more clearly.

    boolean t = true;
    var r = t ? 1 : 2.0;
    System.out.println(r);
    // 1.0
    Integer none = null;
    Integer v = t ? none : 0;
    // throws NullPointerException

How the diagnostic asks it

One question from the Java bank, exactly as a sitting would show it. The bank has 3 on control flow and 30 across Java.

Control Flow · easyJAVA-008

What does this Java code print?

int x = 2;
switch (x) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C");
        break;
    default: System.out.print("D");
}
  1. 1B
  2. 2BCD
  3. 3ABC
  4. 4BCcorrect

Execution jumps to case 2, prints B, and, because case 2 has no break, falls through into case 3, prints C, and stops at the break. B assumes each case ends by itself, which is true in the newer arrow form (case 2 -> ...) but not in this colon form. BCD ignores the break after C. ABC assumes the switch starts at the top rather than at the matching case.

Measure it

Reading answers tells you what’s true. A diagnostic tells you what you get wrong.

10 Java questions across its topics, easy to hard, about fifteen minutes. You get a readiness figure with the arithmetic shown, the topics you missed named, and a practice set sized for today. Free: 1 diagnostic a month and 15 problems a day. No card.

What the readiness test measures · how the score is computed

By Harshit · updated