Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Conditional control flow in Java

Conditional control flow in Java: Java selects control flow with boolean if/else or a switch statement or expression, which in Java 21 supports type and record patterns, when guards, and case null.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

conditions

Java selects control flow with boolean if/else or a switch statement or expression, which in Java 21 supports type and record patterns, when guards, and case null.

Use an arrow-rule switch expression for an enum or sealed hierarchy so the compiler checks exhaustiveness and every branch produces a value.

&& and || short-circuit, whereas & and | evaluate both operands; classic colon case labels can fall through without break.

A broader pattern cannot dominate a later one; null needs an explicit case null, and changing a sealed hierarchy without recompiling a client can yield MatchException.

The output shows the if null guard, a guarded Integer switch case, and String type matching through the text length.

Examples

public class Main {
    static String classify(Object value) {
        if (value == null) return "missing";
        return switch (value) {
            case Integer i when i < 0 -> "negative";
            case Integer i -> "integer:" + i;
            case String s -> "text:" + s.length();
            default -> "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(classify(null));
        System.out.println(classify(-2));
        System.out.println(classify("Java"));
    }
}

Result

missing
negative
text:4

The output shows the if null guard, a guarded Integer switch case, and String type matching through the text length.

Sources