Working with Control Flow Statements

1. Using if-else Statements

FormSyntax
Simpleif (cond) { ... }
if-elseif (cond) { ... } else { ... }
if-else ifif (a) {} else if (b) {} else {}

2. Using Nested if Statements

Example: Nested if

if (user != null) {
    if (user.isAdmin()) {
        if (user.hasPermission("DELETE")) {
            performDelete();
        }
    }
}
TipReason
Use guard clausesReduces nesting depth
Combine with &&Replaces shallow nesting

3. Using switch Statement (traditional)

Example: Traditional switch

switch (day) {
    case MONDAY:
    case TUESDAY:
        System.out.println("Workday");
        break;
    case SATURDAY:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Other");
}
Supported TypeNotes
Integralbyte short int char + wrappers
StringJava 7+
enumUse unqualified constant names
Sealed typesPattern matching (Java 21+)

4. Using Switch Expressions JAVA 14+

Example: Switch expression with arrow

String type = switch (day) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Workday";
    case SATURDAY, SUNDAY -> "Weekend";
};

int len = switch (obj) {
    case String s -> s.length();
    case Integer i -> i;
    default -> 0;
};
FeatureDetail
Arrow syntaxNo fall-through, single expression
yield keywordReturn value from block: { ... yield x; }
ExhaustiveRequired for sealed/enum (no default needed if all cases covered)

5. Understanding Pattern Matching in switch JAVA 21+

Example: Type and record patterns

sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double r) implements Shape {}
record Square(double s) implements Shape {}
record Triangle(double b, double h) implements Shape {}

double area = switch (shape) {
    case Circle(double r)        -> Math.PI * r * r;
    case Square(double s)        -> s * s;
    case Triangle(double b, double h) -> 0.5 * b * h;
};
PatternSyntax
Typecase String s -> ...
Guardedcase Integer i when i > 0 -> ...
Recordcase Point(int x, int y) -> ...
Nullcase null -> ...

6. Using for Loop

FormSyntax
Classicfor (int i=0; i<n; i++) {}
Enhancedfor (var s : collection) {}
Multi-initfor (int i=0, j=n; i<j; i++, j--) {}
Infinitefor (;;) {}

7. Using while Loop

Example: while

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    process(line);
}
AspectDetail
ConditionChecked before each iteration
Zero iterationsPossible if condition false initially

8. Using do-while Loop

Example: do-while

String input;
do {
    input = scanner.nextLine();
} while (!input.equals("quit"));
AspectDetail
ExecutionBody runs at least once
TerminationSemicolon required after while(...)

9. Using break Statement

UseBehavior
Plain breakExits innermost loop/switch
Labeled break labelExits labeled outer loop

Example: Labeled break

outer:
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (matrix[i][j] == target) break outer;
    }
}

10. Using continue Statement

UseBehavior
Plain continueSkip rest of current iteration
Labeled continue labelContinue outer loop

11. Using return Statement

FormUse
return;void methods
return value;typed methods
In finallyOverrides any prior return — avoid

12. Using assert Statement

FormThrows
assert expr;AssertionError if false
assert expr : message;With detail message
EnableJVM flag -ea (disabled by default)
Warning: Don't use assertions for argument validation in public APIs — use explicit exceptions instead.