Skip to content
CodeKruPro

Your language · Java

Conditions and loops

if and else, switch or match, loops, break and continue.

Learn: Conditions and loops in Java7 minute read

Control flow is how a program decides what to run next: conditions pick a branch, and loops repeat code. Interviewers use short "what does this print?" snippets here to check that you read code line by line. Most questions test one of four things: switch fall-through, break versus continue, how many times a loop runs, and the newer switch forms in Java 21.

Step 1: if, else and the ternary operator

if needs a boolean. Java does not treat 0 or null as false, so if (count) does not compile. Chain conditions with else if. The operators && and || short-circuit, which means they stop as soon as the answer is known. In if (el != null && el.isDisplayed()) the second check runs only when the first is true, so it never hits a null. For a choice between two values, the ternary operator is shorter: String label = passed ? "PASS" : "FAIL";.

Step 2: the classic switch statement

A classic switch uses case 2: labels with a colon. It jumps to the matching case and then runs every statement below it until it meets a break. Running on into the next case is called fall-through. Forgetting a break is a common bug and a common interview question.

A classic switch works on int and the smaller integer types, char, their wrappers (objects that hold one primitive value, for example Integer), String and enums (a fixed list of named constants; see Basics). String cases are matched with equals, so they are case-sensitive. A switch on long, double or boolean does not compile.

Step 3: switch expressions and pattern matching

Since Java 14 a switch can be an expression that returns a value. Arrow labels (case 2 ->) never fall through, one case can list several values, and a block returns its value with yield. The compiler checks that every possible input is covered. An int or String switch therefore needs a default, while an enum switch is complete when it lists every constant.

Java 21 added pattern matching for switch (a case can check what type a value is). A case can test the type of a value and give it a name, add a when condition (a guard), and handle case null. The same idea works in an if: if (value instanceof String s && !s.isBlank()) tests and casts in one step.

public class Main {
    enum Env { DEV, QA, PROD }

    static String describe(Object o) {
        return switch (o) {
            case null -> "nothing";
            case Integer i when i > 100 -> "large number";
            case Integer i -> "number " + i;
            case String s -> "text of length " + s.length();
            default -> "something else";
        };
    }

    public static void main(String[] args) {
        int day = 2;
        switch (day) {               // classic: falls through without break
            case 1: System.out.print("Mon ");
            case 2: System.out.print("Tue ");
            case 3: System.out.print("Wed "); break;
            default: System.out.print("Other ");
        }
        System.out.println();

        Env env = Env.QA;
        String url = switch (env) {   // expression: no break, must cover all
            case DEV -> "http://localhost:8080";
            case QA -> "https://qa.example.com";
            case PROD -> "https://example.com";
        };
        System.out.println(url);

        System.out.println(describe(500) + " | " + describe(7) + " | " + describe("abc") + " | " + describe(null));
    }
}
Tue Wed
https://qa.example.com
large number | number 7 | text of length 3 | nothing

The classic switch started at case 2, printed "Tue ", fell into case 3 and stopped at its break.

Step 4: the four loops

  • A counting for loop, when you need the index, such as walking table rows by position.
  • An enhanced for loop (for-each), the simplest way to read every element of an array or collection. You cannot remove items from a collection (a list, set or map) inside it; use an Iterator (an object that walks through a collection and can remove items safely) or removeIf (a collection method that deletes every item matching a test). See Collections.
  • A while loop, when you do not know how many passes you need, such as polling until a file exists.
  • A do-while loop, which checks its condition at the end, so the body always runs at least once.

Step 5: break, continue and labels

break leaves the nearest loop (or switch) at once. continue skips the rest of the current pass and starts the next one. Both act on the innermost loop. To act on an outer loop, put a label before it and write break outer; or continue outer;.

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) continue;
            if (i == 5) break;
            System.out.print(i + " ");
        }
        System.out.println();

        int tries = 10;
        do {
            System.out.println("attempt " + tries);
            tries++;
        } while (tries < 5);

        String[][] table = { {"Asha", "QA"}, {"Ravi", "Dev"}, {"Bea", "QA"} };
        search:
        for (String[] row : table) {
            for (String cell : row) {
                if (cell.equals("Dev")) {
                    System.out.println("found in row of " + row[0]);
                    break search;
                }
            }
        }
    }
}
1 2 4
attempt 10
found in row of Ravi

For for (int i = a; i < b; i++) the body runs b - a times; with <= it runs once more. In test code this matters for tables, where row 0 is often the header:

List<WebElement> rows = driver.findElements(By.cssSelector("table tr"));
for (int i = 1; i < rows.size(); i++) {   // skip the header row at index 0
    System.out.println(rows.get(i).getText());
}

How to answer in an interview

For an output question, trace the code out loud and write the value of each variable after every pass. Say what each keyword does at the moment it runs: "When i is 3, continue skips the print. When i is 5, break runs before the print, so the output is 1 2 4." For a theory question such as "break versus continue", give the one-line rule, then a test example: "I break out of a search loop once I find the row, and I continue past empty cells when I add up prices."

Common mistakes

  • Forgetting break in a classic switch, or adding it to arrow cases, where it is not needed.
  • Thinking continue ends the loop. It only ends the current pass.
  • Off-by-one counts: mixing up < and <=, or reading the header row as data.
  • Removing items from a list inside a for-each loop, which throws ConcurrentModificationException (the error Java gives when a collection changes while a loop is reading it).
  • Writing a waiting loop with no time limit. In Selenium (a tool that controls a web browser from code), use an explicit wait (a built-in wait that stops after a set time) instead.

Recap

Conditions need a real boolean. A classic switch falls through until break; arrow cases never do, and switch expressions must cover every value. Java 21 can switch on types with guards and case null. Pick the loop by what you know: the count, the collection, a condition, or "at least once". break leaves a loop, continue skips one pass, and labels aim either one at an outer loop.

8 questions0/8 solved

Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan