Tutorials / Java: From Zero to Advanced / Control flow: if, switch expressions and loops

Control flow: if, switch expressions and loops

14 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Choosing a path

Programs make decisions and repeat work. This lesson covers the tools for both. If you know another language, most of it will look familiar. Pay attention to the switch expression, which is one of the best improvements in modern Java.

if, else if, else

An if needs a condition of type boolean. Java does not accept numbers or strings as conditions, so if (count) is an error. Use braces even for one-line bodies. Skipping them is a classic source of bugs when somebody adds a second line later.

switch expressions

The old switch statement needed break at the end of every case and fell through when you forgot it. Since Java 14 you can write a switch expression with arrows. It produces a value, it does not fall through, and the compiler checks that all cases are covered.

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        // if / else if
        int score = 72;
        if (score >= 90) {
            System.out.println("Grade A");
        } else if (score >= 75) {
            System.out.println("Grade B");
        } else if (score >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Fail");
        }

        // switch expression with arrows and multiple labels
        String day = "SATURDAY";
        String type = switch (day) {
            case "SATURDAY", "SUNDAY" -> "weekend";
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "weekday";
            default -> throw new IllegalArgumentException("Unknown day: " + day);
        };
        System.out.println(day + " is a " + type);

        // switch with a block and yield
        int month = 2;
        int days = switch (month) {
            case 2 -> {
                boolean leap = false;
                yield leap ? 29 : 28;
            }
            case 4, 6, 9, 11 -> 30;
            default -> 31;
        };
        System.out.println("Days: " + days);

        // for loop: a multiplication table
        for (int i = 1; i <= 5; i++) {
            System.out.printf("7 x %d = %d%n", i, 7 * i);
        }

        // while loop: halve until small
        double value = 100;
        int steps = 0;
        while (value > 1) {
            value /= 2;
            steps++;
        }
        System.out.println("Steps: " + steps);

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

        // enhanced for loop
        String[] fruits = {"mango", "apple", "guava"};
        for (String fruit : fruits) {
            System.out.println("I like " + fruit);
        }

        // break and continue: first 5 primes
        List<Integer> primes = new ArrayList<>();
        for (int n = 2; primes.size() < 5; n++) {
            boolean isPrime = true;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (!isPrime) {
                continue;
            }
            primes.add(n);
        }
        System.out.println(primes);

        // A labelled break leaves both loops
        search:
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 3; col++) {
                if (row * col == 6) {
                    System.out.println("Found at " + row + "," + col);
                    break search;
                }
            }
        }
    }
}

Walking through it

The first switch uses string cases. Several labels share one result with commas. Because it is an expression, we assign it to type directly. With default throwing an exception, we never end up with an unset value. When you switch on an enum or a sealed type and cover every case, you can leave out default, and the compiler will tell you if a case is missing. That check is why I prefer switch expressions to long if chains.

The second switch shows a block with yield. When a case needs more than one expression, wrap it in braces and use yield to give back the value. (In real code, the leap-year check would use a calculation.)

The for loop has three parts: initialisation, condition, update. i++ adds one after each pass. The while loop checks first, so it may run zero times. The do-while loop checks at the end, so it runs at least once. Both of those are chosen when you do not know in advance how many rounds you need.

The enhanced for loop reads as "for each fruit in fruits". It works on arrays and on any collection. It has no index to get wrong, so use it whenever you do not need the position.

The prime search combines break and continue. break leaves the inner loop as soon as a divisor is found. continue skips the rest of the current pass of the outer loop. The loop condition primes.size() < 5 keeps going until we have five. A label on a loop, such as search:, lets break search leave an outer loop from inside an inner one. Use labels rarely. Often a method with return is clearer.

Reading input

To read from the keyboard, use Scanner: Scanner in = new Scanner(System.in); and then in.nextLine() for text or in.nextInt() for a number. Remember that nextInt leaves the line break in the input, so call nextLine() once afterwards before reading text. Better still, read every line with nextLine() and convert it with Integer.parseInt, which throws NumberFormatException on bad input. You will handle that in the exceptions lesson.

Common mistakes

  • Using = in a condition. if (x = 5) does not compile for ints, but if (flag = true) does and assigns.
  • A semicolon right after the if or for brackets. It becomes an empty body.
  • Off-by-one errors in loop limits. Check the first and last pass on paper.
  • Forgetting break in an old-style switch. Arrow syntax avoids it.
  • Infinite loops. Make sure something in the loop moves the condition toward false.

Try it yourself

  1. Print the numbers 1 to 30, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5 and "FizzBuzz" for both.
  2. Write a switch expression that converts a number from 1 to 7 into a day name and throws an exception for other values.
  3. Use a Scanner to build a guessing game with a secret number and "higher" or "lower" hints.
java
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        // if / else if
        int score = 72;
        if (score >= 90) {
            System.out.println("Grade A");
        } else if (score >= 75) {
            System.out.println("Grade B");
        } else if (score >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Fail");
        }

        // switch expression with arrows and multiple labels
        String day = "SATURDAY";
        String type = switch (day) {
            case "SATURDAY", "SUNDAY" -> "weekend";
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "weekday";
            default -> throw new IllegalArgumentException("Unknown day: " + day);
        };
        System.out.println(day + " is a " + type);

        // switch with a block and yield
        int month = 2;
        int days = switch (month) {
            case 2 -> {
                boolean leap = false;
                yield leap ? 29 : 28;
            }
            case 4, 6, 9, 11 -> 30;
            default -> 31;
        };
        System.out.println("Days: " + days);

        // for loop: a multiplication table
        for (int i = 1; i <= 5; i++) {
            System.out.printf("7 x %d = %d%n", i, 7 * i);
        }

        // while loop: halve until small
        double value = 100;
        int steps = 0;
        while (value > 1) {
            value /= 2;
            steps++;
        }
        System.out.println("Steps: " + steps);

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

        // enhanced for loop
        String[] fruits = {"mango", "apple", "guava"};
        for (String fruit : fruits) {
            System.out.println("I like " + fruit);
        }

        // break and continue: first 5 primes
        List<Integer> primes = new ArrayList<>();
        for (int n = 2; primes.size() < 5; n++) {
            boolean isPrime = true;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (!isPrime) {
                continue;
            }
            primes.add(n);
        }
        System.out.println(primes);

        // A labelled break leaves both loops
        search:
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 3; col++) {
                if (row * col == 6) {
                    System.out.println("Found at " + row + "," + col);
                    break search;
                }
            }
        }
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account