Decisions and loops

Introduction

Programs become useful when they can decide and repeat: grade a mark, retry until the input is right, process every line of a file. Java's control flow looks like C's and JavaScript's, with one modern addition worth learning early, the switch expression. This lesson covers the statements that decide which code runs, and how many times.

How it works

if runs a block when a condition is true. Conditions are boolean expressions built from comparisons (==, !=, <, <=, >, >=) and combined with && (and), || (or) and ! (not). else if adds more cases and else catches the rest; Java checks them in order and runs only the first that matches.

if (mark >= 80) grade = "A";
else if (mark >= 60) grade = "B";
else grade = "C";

&& and || stop as soon as the answer is known, so x != 0 && 10 / x > 1 never divides by zero. Strings must be compared with equals, not ==, as the strings lesson explains.

A switch chooses among fixed values. The classic switch statement needs break after each case, or it falls through to the next. Since Java 14, a switch expression is shorter and safer: each case has an arrow, several labels can share a case, there is no fall-through, and the whole switch produces a value:

String note = switch (grade) {
    case "A" -> "excellent";
    case "B", "C" -> "pass";
    default -> "try again";
};

Loops repeat. A for loop puts the start, the condition and the update on one line, which suits a known number of passes: for (int i = 0; i < n; i++). A while loop checks its condition first and suits an unknown number, such as reading until the input ends: while (in.hasNextInt()). A do-while runs its body once before checking, which suits menus and retries. The enhanced for loop, for (int x : array), visits every item of an array or collection.

Inside a loop, break leaves it at once and continue skips to the next pass. Variables declared inside a block exist only inside it, so the loop counter i is gone after the loop.

Example

// Decisions and loops: if/else, a switch expression, for and while.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int passed = 0;
        for (int i = 0; i < n; i++) {
            int mark = in.nextInt();
            String grade;
            if (mark >= 80) grade = "A";
            else if (mark >= 60) grade = "B";
            else if (mark >= 40) grade = "C";
            else grade = "F";
            if (!grade.equals("F")) passed++;
            String note = switch (grade) {
                case "A" -> "excellent";
                case "B", "C" -> "pass";
                default -> "try again";
            };
            System.out.println(mark + ": " + grade + " (" + note + ")");
        }
        int k = 1;
        while (k * k < 50) k++;
        System.out.println(passed + " of " + n + " passed; the first square over 50 is " + k * k);
    }
}

Input used: 4 ⏎ 85 62 30 45

Open in compiler

Line by line

  1. The for loop runs once per mark; n was read first.
  2. The if chain picks the first grade whose condition is true.
  3. !grade.equals("F") counts every grade except F.
  4. The switch expression turns the grade into a note; B and C share a case.
  5. The while loop has no fixed count: it stops when k * k reaches 50.

Expected result

With this input:

4
85 62 30 45

With this input:

4
85 62 30 45

it prints:

85: A (excellent)
62: B (pass)
30: F (try again)
45: C (pass)
3 of 4 passed; the first square over 50 is 64

In the real world

Every business rule is a condition: discounts, access rights, shipping costs, tax bands. Switch expressions are popular in modern Java code for mapping states and codes to actions, because the compiler can check that an enum's cases are all handled. Loops process records, retry network calls and poll for work.

Common mistakes

  • Using = instead of == in a condition (javac rejects it for ints, so the error is at least caught).
  • Forgetting break in a classic switch statement, so cases fall through.
  • Off-by-one loop bounds, such as i <= n when indexes go to n - 1.
  • Changing a while loop's condition never, so it never ends.

Best practices

  • Prefer switch expressions with arrows to classic switch statements.
  • Use the enhanced for loop when you do not need the index.
  • Keep conditions simple; give complex ones a name with a boolean variable.

Summary

if, else if and else choose one branch by boolean conditions, combined with &&, || and !. Switch expressions map values to results without fall-through. for loops suit a known number of passes, while and do-while an unknown one, and break and continue leave or skip passes early.

Quick check

1. Which loop suits reading numbers until the input runs out?
2. What happens in a classic switch statement without break?
3. Why is x != 0 && 10 / x > 1 safe when x is 0?
4. How many times does a do-while body run if its condition is false at the start?

Key takeaways

  • if / else if / else picks one branch; && and || combine conditions, and ! negates one.
  • A switch expression maps cases to values with ->; several labels can share one case.
  • Use for when you know how many passes, while when you do not, and do-while when the body must run once first.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.