Beginner

Control Flow in Java

Learn conditionals, switch expressions, and loops in Java with practical Docker-ready examples covering if/else, for, while, and loop control

Control flow is how a program decides what to do next. Instead of running every line top to bottom, control flow lets your code branch based on conditions and repeat work with loops. Mastering it is the difference between a program that follows a fixed script and one that reacts to data.

As a statically typed, class-based object-oriented language, Java inherits its control flow syntax from the C family — curly braces delimit blocks, parentheses wrap conditions, and conditions must evaluate to a boolean (not an integer, as in C). This strict typing means the compiler rejects accidental mistakes like if (x = 5) that silently bite you in other languages.

In this tutorial you’ll learn Java’s conditional statements (if/else if/else), the ternary operator, modern switch expressions introduced in recent Java versions, and the four loop forms (for, enhanced for, while, and do-while) along with the break and continue keywords that fine-tune iteration.

Conditionals: if, else if, and the Ternary Operator

The if statement runs a block only when its boolean condition is true. Chain conditions with else if, and provide a fallback with else. For simple value selection, the ternary operator condition ? a : b is a compact one-line alternative.

Create a file named Conditionals.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Conditionals {
    public static void main(String[] args) {
        int score = 82;

        // if / else if / else chain
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }

        // Ternary operator: a compact conditional expression
        int temperature = 15;
        String weather = (temperature > 20) ? "warm" : "cool";
        System.out.println("It is " + weather + " today");

        // Conditions must be boolean — combine them with && and ||
        boolean isWeekend = false;
        boolean isHoliday = true;
        if (isWeekend || isHoliday) {
            System.out.println("No work today!");
        }
    }
}

Note that Java requires the condition inside if (...) to be a genuine boolean. Writing if (score) with an int is a compile error — a deliberate guardrail that catches a whole class of bugs.

Switch Expressions

When you need to branch on a single value across many cases, a switch is cleaner than a long if/else if chain. Modern Java (14+) provides switch expressions using arrow (->) syntax. Unlike the old switch statement, arrows don’t “fall through” to the next case, so no break is needed, and the whole switch can return a value.

Create a file named SwitchExample.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;

        // Switch expression returns a value — no break, no fall-through
        String name = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            default -> "Weekend";
        };
        System.out.println("Day " + day + " is " + name);

        // Multiple labels can share one branch
        String kind = switch (day) {
            case 6, 7 -> "rest day";
            default -> "work day";
        };
        System.out.println("Day " + day + " is a " + kind);
    }
}

The default branch is required when the switch is used as an expression that must always produce a value, ensuring every possible input is handled.

Loops: for, for-each, while, and do-while

Loops repeat a block of code. Java offers four forms:

  • for — best when you know the iteration count or need an index counter.
  • Enhanced for (for-each) — iterates over every element of an array or collection.
  • while — repeats as long as a condition holds, checking before each pass.
  • do-while — like while, but checks after each pass, so the body always runs at least once.

Create a file named Loops.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Loops {
    public static void main(String[] args) {
        // Classic for loop with an index counter
        System.out.print("Squares:");
        for (int i = 1; i <= 5; i++) {
            System.out.print(" " + (i * i));
        }
        System.out.println();

        // Enhanced for loop (for-each) over an array
        String[] languages = {"Java", "Kotlin", "Scala"};
        for (String lang : languages) {
            System.out.println("JVM language: " + lang);
        }

        // while loop: condition checked before each iteration
        int countdown = 3;
        while (countdown > 0) {
            System.out.println("T-minus " + countdown);
            countdown--;
        }
        System.out.println("Liftoff!");

        // do-while loop: body runs at least once
        int attempts = 0;
        do {
            attempts++;
            System.out.println("Attempt " + attempts);
        } while (attempts < 2);
    }
}

Loop Control: break and continue

Inside any loop, break exits the loop immediately, while continue skips the rest of the current iteration and moves to the next one. They let you short-circuit work without restructuring the loop condition.

Create a file named LoopControl.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class LoopControl {
    public static void main(String[] args) {
        System.out.print("Odd numbers under 10:");
        for (int n = 1; n < 20; n++) {
            if (n >= 10) {
                break;       // stop the loop entirely once we hit 10
            }
            if (n % 2 == 0) {
                continue;    // skip even numbers
            }
            System.out.print(" " + n);
        }
        System.out.println();
    }
}

Running with Docker

Each example is a standalone class. Compile and run it inside the official Eclipse Temurin JDK image — no local Java installation required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Pull the official Eclipse Temurin JDK image
docker pull eclipse-temurin:21-jdk

# Run the conditionals example
docker run --rm -v $(pwd):/app -w /app eclipse-temurin:21-jdk \
    sh -c "javac Conditionals.java && java Conditionals"

# Run the switch example
docker run --rm -v $(pwd):/app -w /app eclipse-temurin:21-jdk \
    sh -c "javac SwitchExample.java && java SwitchExample"

# Run the loops example
docker run --rm -v $(pwd):/app -w /app eclipse-temurin:21-jdk \
    sh -c "javac Loops.java && java Loops"

# Run the loop control example
docker run --rm -v $(pwd):/app -w /app eclipse-temurin:21-jdk \
    sh -c "javac LoopControl.java && java LoopControl"

Expected Output

Running Conditionals:

Grade: B
It is cool today
No work today!

Running SwitchExample:

Day 3 is Wednesday
Day 3 is a work day

Running Loops:

Squares: 1 4 9 16 25
JVM language: Java
JVM language: Kotlin
JVM language: Scala
T-minus 3
T-minus 2
T-minus 1
Liftoff!
Attempt 1
Attempt 2

Running LoopControl:

Odd numbers under 10: 1 3 5 7 9

Key Concepts

  • Conditions must be boolean — Java rejects if (x = 5) or if (someInt) at compile time, eliminating a common C-family bug.
  • Ternary for compact choicescondition ? a : b is an expression that returns a value, ideal for simple assignments.
  • Switch expressions are modern and safe — arrow (->) syntax has no fall-through, needs no break, and can return a value directly.
  • Four loop forms, each with a purpose — use for for counters, enhanced for for collections, while for condition-driven repetition, and do-while when the body must run at least once.
  • do-while always runs once — its condition is checked after the body, unlike while which checks before.
  • break and continue refine loopsbreak exits a loop entirely; continue skips to the next iteration.
  • Curly braces are best practice — while Java allows single-statement bodies without braces, always using { } prevents subtle errors when code is later edited.

Running Today

All examples can be run using Docker:

docker pull eclipse-temurin:21-jdk
Last updated:

Comments

Loading comments...

Leave a Comment

2000 characters remaining