Jack Ng

Essay

Learning Java, Part 3: Control Statements

Study notes on if and else-if ladders, the switch statement and its fall-through, for, enhanced for, while and do-while loops, break, labelled break and continue, and nested loops. Written entirely by an AI model.

Java’s control statements look like C’s. If you know Python’s if and loops, the ideas are the same; what changes is the syntax and a few statements Python lacks, notably switch and do-while.

Reading a key from the keyboard

The book starts this chapter with System.in.read(), which reads one byte. Real programs use Scanner instead:

import java.util.Scanner;

public class AskCups {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("How many cups? ");
        if (in.hasNextInt()) {
            int cups = in.nextInt();
            System.out.println("Brewing " + cups);
        } else {
            System.out.println("No number given.");
        }
    }
}
How many cups? No number given.

The output above is what you get when nothing is typed. nextInt(), nextDouble() and nextLine() read the next value; hasNextInt() checks first, so the program does not crash on bad input. One trap: after nextInt(), the newline the user typed is still waiting, so a following nextLine() returns an empty string. Call nextLine() once to discard it.

if, else if and else

public class Grade {
    public static void main(String[] args) {
        int mark = 73;
        String grade;
        if (mark >= 80) {
            grade = "HD";
        } else if (mark >= 70) {
            grade = "D";
        } else if (mark >= 60) {
            grade = "CR";
        } else if (mark >= 50) {
            grade = "P";
        } else {
            grade = "N";
        }
        System.out.println(grade);
    }
}
D

This is the if-else-if ladder. The first true condition wins and the rest are skipped. Python’s elif is spelled else if in Java.

An else belongs to the nearest if that has no else, whatever the indentation says. This “dangling else” is one reason to always use braces:

if (a > 0)
    if (b > 0) System.out.println("both");
else System.out.println("this runs when a > 0 and b <= 0");

The compiler also catches a mistake that bites Python beginners less often: because conditions must be boolean, if (x = 5) is an error rather than a silent assignment.

switch

switch chooses among constant values of an integer type, char, String or an enum (Part 12):

public class Day {
    public static void main(String[] args) {
        int day = 6;
        switch (day) {
            case 1:
            case 7:
                System.out.println("market day");
                break;
            case 6:
                System.out.println("cleaning");
                // no break: falls through
            case 2:
                System.out.println("deliveries");
                break;
            default:
                System.out.println("ordinary");
        }
    }
}
cleaning
deliveries
  • Execution jumps to the matching case and then runs every following statement until a break or the end. Forgetting break is the most common switch bug; stacking case 1: case 7: on purpose is the useful side of it.
  • default runs when nothing matches. It is optional.
  • case labels must be constants and unique. Switches can be nested.

Modern Java. Since Java 14, the arrow form never falls through and can produce a value:

public class ArrowSwitch {
    public static void main(String[] args) {
        String size = "M";
        int ml = switch (size) {
            case "S" -> 250;
            case "M", "L" -> 350;
            default -> throw new IllegalArgumentException(size);
        };
        System.out.println(ml);
    }
}
350

Learn both. The book, and older exams, use the colon form.

for loops

for (initialisation; condition; update) body

The initialisation runs once; the condition is checked before each pass; the update runs after each pass. All three parts are optional, and any can be a comma-separated list:

public class TwoEnds {
    public static void main(String[] args) {
        for (int i = 0, j = 10; i < j; i += 3, j -= 3) {
            System.out.println(i + " " + j);
        }
    }
}
0 10
3 7
  • for (;;) with every part empty is an infinite loop, ended with break.
  • A loop control variable declared in the for exists only inside the loop.
  • A semicolon right after the header, for (int i = 0; i < 5; i++);, gives a loop with an empty body. It compiles, so watch for it.

The enhanced for

To visit every element of an array or collection, use the enhanced for (often called for-each), the closest thing to Python’s for x in items:

public class Prices {
    public static void main(String[] args) {
        double[] prices = {4.5, 3.0, 5.25};
        double sum = 0;
        for (double p : prices) {
            sum += p;
        }
        System.out.println(sum);
    }
}
12.75

Read the colon as “in”. You get each value but not its index, and assigning to p does not change the array.

while and do-while

while checks its condition before each pass and may run zero times. do-while checks after, so its body always runs at least once, which suits “ask until valid” loops:

public class Halving {
    public static void main(String[] args) {
        int n = 100;
        int steps = 0;
        while (n > 1) {
            n /= 2;
            steps++;
        }
        System.out.println(steps);

        int tries = 0;
        do {
            tries++;
        } while (tries < 0);   // false at once, but the body ran
        System.out.println(tries);
    }
}
6
1

Note the semicolon after the while (...) of a do-while.

break and continue

break leaves the innermost loop (or switch). continue skips to the next pass. Java has no goto, but a labelled break leaves an outer loop directly, which is the clean way to stop a nested search:

public class FindPair {
    public static void main(String[] args) {
        int[] a = {3, 8, 1, 6};
        search:
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] + a[j] == 7) {
                    System.out.println("indexes " + i + " and " + j);
                    break search;
                }
            }
        }
        for (int k = 1; k <= 6; k++) {
            if (k % 2 == 0) continue;
            System.out.print(k + " ");
        }
        System.out.println();
    }
}
indexes 2 and 3
1 3 5

The label (search:) goes immediately before the loop. continue search; also works and starts the outer loop’s next pass.

Nested loops

A loop inside a loop runs the inner one completely for every pass of the outer one. The classic exercise prints the factors of each number:

public class Factors {
    public static void main(String[] args) {
        for (int n = 2; n <= 6; n++) {
            System.out.print(n + ":");
            for (int f = 2; f <= n / 2; f++) {
                if (n % f == 0) System.out.print(" " + f);
            }
            System.out.println();
        }
    }
}
2:
3:
4: 2
5:
6: 2 3

Exam-style checks

  • What does a switch print when a case has no break? Give a case where that is useful.
  • Rewrite a do-while as a while and explain why they behave differently when the condition starts false.
  • Show how a labelled break ends two nested loops at once.
  • Why is for (int i = 0; i < 5; i++); followed by System.out.println(i); a compile error?

Where to practise

Schildt builds a small help system across the chapter’s three “Try This” exercises, using switch, then a do-while menu, then break to exit. Write your own version for a café menu. Then write a program that prints a multiplication table with nested for loops, and another that reads numbers with a Scanner until the user types 0 and prints their total.