Control flow statements decide which code runs and how often. Java has three groups: decision statements (if, switch), loops (for, enhanced for, while, do-while) and jump statements (break, continue, return). Below is each one with examples from test code and the mistakes to avoid.

if, else if and else

int status = response.getStatusCode();
if (status == 200) {
    System.out.println("OK");
} else if (status == 401 || status == 403) {
    System.out.println("Auth problem");
} else if (status >= 500) {
    System.out.println("Server error");
} else {
    System.out.println("Unexpected: " + status);
}

Conditions are checked top to bottom and only the first true branch runs. Always use braces, even for one line; adding a second line later without braces is a classic bug.

Advertisement

The switch Statement

The classic switch compares one value against constants. It works with int and smaller integer types, char, String and enums. Without break, execution falls through into the next case:

switch (browser) {
    case "chrome":
        driver = new ChromeDriver();
        break;
    case "firefox":
        driver = new FirefoxDriver();
        break;
    default:
        throw new IllegalArgumentException("Unsupported browser: " + browser);
}

Switch Expressions (Java 14+)

The arrow form has no fall-through, can list several labels per case, and can return a value. The compiler also checks that every enum value is covered when there's no default:

WebDriver driver = switch (browser) {
    case "chrome", "chrome-headless" -> new ChromeDriver();
    case "firefox" -> new FirefoxDriver();
    case "edge" -> new EdgeDriver();
    default -> throw new IllegalArgumentException("Unsupported browser: " + browser);
};

Use yield to return a value from a case that needs a block of code. Prefer this form in new code: it's shorter and removes the forgotten-break bug.

The for Loop

for (int i = 0; i < rows.size(); i++) {
    System.out.println(i + ": " + rows.get(i).getText());
}

The three parts are initialisation, condition and update. Use it when you need the index. A common off-by-one error is i <= list.size(), which throws IndexOutOfBoundsException on the last pass.

The Enhanced for Loop (for-each)

for (WebElement link : driver.findElements(By.tagName("a"))) {
    System.out.println(link.getAttribute("href"));
}

It's the clearest way to visit every element of an array or collection. You can't get the index, and you mustn't add or remove elements of the collection inside it, which throws ConcurrentModificationException; use an Iterator or removeIf() instead.

while and do-while

while checks the condition before each pass, so it may run zero times. do-while checks after, so it always runs at least once.

// Poll a job status, at most 10 times
int attempts = 0;
String state = api.getJobState(jobId);
while (!state.equals("DONE") && attempts < 10) {
    Thread.sleep(2000);
    state = api.getJobState(jobId);
    attempts++;
}

// Ask at least once
String input;
do {
    input = scanner.nextLine();
} while (input.isBlank());

Every loop needs a way out. In polling code, always add a maximum number of attempts or a timeout, otherwise a stuck job hangs your whole test run.

break, continue and Labels

  • break leaves the nearest loop or switch immediately.
  • continue skips to the next iteration.
  • A labelled break leaves an outer loop from inside an inner one.
search:
for (WebElement row : rows) {
    for (WebElement cell : row.findElements(By.tagName("td"))) {
        if (cell.getText().equals("Order #1042")) {
            row.findElement(By.cssSelector(".view")).click();
            break search;            // exits both loops
        }
    }
}

return

return leaves the method, optionally with a value. Returning early from a helper often reads better than deeply nested if blocks:

boolean isPresent(By locator) {
    if (driver.findElements(locator).isEmpty()) return false;
    return driver.findElement(locator).isDisplayed();
}

Which Statement Should You Use?

SituationUse
Two or three different conditionsif / else if / else
One value compared with many constantsSwitch expression
Visit every item, no index neededEnhanced for
Need the index or a step other than 1Classic for
Repeat until something changeswhile with a maximum
Must run at least oncedo-while

FAQs

What are the types of control flow statements in Java?

Decision statements (if, if-else, switch), loops (for, enhanced for, while, do-while) and jump statements (break, continue, return).

What is the difference between while and do-while?

while checks its condition before each iteration, so it can run zero times; do-while checks after, so its body always runs at least once.

What happens if you forget break in a switch?

In a classic switch, execution falls through into the next case and runs its code too. The arrow form of switch (Java 14+) has no fall-through.

Can a switch use strings in Java?

Yes, since Java 7. A switch works with int and smaller integer types, char, their wrapper classes, String and enums; newer versions also add pattern matching.