BeginnerLesson 4 of 204 min read

Decisions and Loops: if, switch and the Loops That Repeat

Learn if statements, switch expressions, while, for and enhanced for loops, and use them to price bike rentals, with results checked by an independent calculation.

In this lesson you will

  • Make decisions with if and switch
  • Repeat work with for and while
  • Use break and continue
  • Check a loop with a second method

About 28 minutes

Prices that depend on the day

Hana charges different prices for weekdays and weekends, and gives a discount for long rentals. A program needs decisions to choose the right price, and loops to go through many rentals. Decisions use if and switch, and loops use for, while and the enhanced for loop that walks through a collection.

An if statement runs a block only when its condition is true, and else covers the rest. A switch chooses between many fixed values. Since Java 14 a switch can be an expression that produces a value and uses arrows, with no fall-through and a requirement that all cases are covered, which makes it much safer than the old form. A for loop has a start, a condition and a step, a while loop checks its condition first, and break and continue let you leave a loop or skip to the next round.

Construct Use it when
if / else One or two conditions
switch expression Choosing by a fixed set of values
for You know how many rounds
while You repeat until something changes
for-each You visit every item of an array or collection
public class Main {
    static int dayPrice(String day) {
        return switch (day) {
            case "SAT", "SUN" -> 18;
            case "FRI" -> 15;
            default -> 12;
        };
    }
    public static void main(String[] args) {
        String[] days = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
        int week = 0;
        for (String d : days) {
            int p = dayPrice(d);
            week += p;
            System.out.println(d + " costs " + p);
        }
        System.out.println("one bike for the whole week: " + week);
        int rental = 5;
        int total = rental * 12;
        if (rental >= 5) { total = total * 90 / 100; }
        System.out.println("5-day rental with 10% off: " + total);
        int n = 0, steps = 0;
        while (n < 100) { n += 7; steps++; }
        System.out.println("while loop: reached " + n + " after " + steps + " steps");
        int evens = 0;
        for (int i = 1; i <= 20; i++) {
            if (i % 2 == 1) continue;
            if (i > 14) break;
            evens += i;
        }
        System.out.println("sum of even numbers up to 14: " + evens);
    }
}
MON costs 12
TUE costs 12
WED costs 12
THU costs 12
FRI costs 15
SAT costs 18
SUN costs 18
one bike for the whole week: 99
5-day rental with 10% off: 54
while loop: reached 105 after 15 steps
sum of even numbers up to 14: 56

The switch expression priced Saturday and Sunday at 18, Friday at 15 and the other four days at 12, so a whole week for one bike costs 99. The 5-day rental is 60 before the discount and 54 after taking 10 percent off, and note that the program multiplies by 90 before dividing by 100, which keeps the arithmetic in whole numbers. The while loop added 7 until it passed 100 and stopped at 105 after 15 steps. The last loop skipped odd numbers with continue and left the loop with break when the number passed 14, so it added 2 + 4 + 6 + 8 + 10 + 12 + 14, which is 56.

Check by hand: five days at 12 is 60, ten percent of 60 is 6, and 60 – 6 = 54. For the week, 12 x 4 + 15 + 18 x 2 = 48 + 15 + 36 = 99. The loop reaches 105 because 15 x 7 = 105 is the first multiple of 7 that is not below 100, and 14 x 7 = 98 was still below it. An independent Python calculation of the same rules produced the same totals, which the module asserts before the lesson was written.

Reading a loop like the computer does

When a loop confuses you, write down the variables for each round on paper, as a small table. For the while loop above the table would show n as 7, 14, 21 and so on, with the step count rising by one each time, and the loop ends in the round where the condition n < 100 first becomes false. Doing this once or twice trains your eye, and it is the fastest way to find an off-by-one error without a debugger.

Beware of off-by-one errors

Whether a loop uses < or <= decides whether it runs the last round. Test with a tiny case where you know the answer.

Prefer switch expressions

They return a value, need no break statements and the compiler checks that every case is covered, for enums and sealed types.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. Switch expressions need Java 14 or later.

Practice

Write a loop that prints the price table for 1 to 10 rental days with the 10 percent discount from 5 days on. Then change the switch so that a holiday costs 20, and check that the week total changes by the right amount.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a switch expression return?

  1. A value
  2. Nothing
  3. Always a string
  4. A class

You can assign it to a variable.

What does continue do in a loop?

  1. Leaves the loop
  2. Ends the program
  3. Repeats the same round
  4. Skips to the next round

break leaves the loop.

Which loop checks its condition before the first round?

  1. do-while
  2. Neither
  3. Both always run once
  4. while

do-while checks at the end.

What does a for-each loop visit?

  1. Only the first item
  2. Only numbers
  3. Every item of an array or collection
  4. Only strings

No index needed.

What was the week total?

  1. 90
  2. 108
  3. 99
  4. 84

12 x 4 + 15 + 18 x 2.

Summary

  • Use if for conditions and switch expressions for choices between fixed values.
  • for, while and for-each repeat work.
  • break leaves a loop and continue skips a round.
  • Check loops against a hand calculation.

Next lesson

Lesson 5 covers methods: how to name, reuse and test pieces of logic.

Questions

When should I use a switch instead of if?

When one value is compared against several fixed possibilities. It reads better than a chain of if statements.

What is the ternary operator?

condition ? a : b is a short if-else that produces a value.

Can a loop run forever?

Yes, if its condition never becomes false. Use break or a changing condition to end it.

Progress is saved in this browser.