CodeBlanks Logo Icon CodeBlanks

switch

Learn multi-branch with switch.

switch

switch branches on the value of a variable. case lists values, break exits, default is the fallback branch.

int day = 1;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Unknown");
}

switch works with int, String, enum and wrapper types. Without break; after a case, execution falls through to the next case; this is called fall-through.

switch flow

Without break, execution falls through to the next case. This is called fall-through:

int day = 1;
switch (day) {
    case 1:
    case 2:
        System.out.println("Weekday");
        break;
    default:
        System.out.println("Weekend");
}

Here both 1 and 2 print "Weekday". Fall-through is useful to bind several values to the same block. Forgetting break by mistake is a common error; write each branch carefully.

Practice Print the day name

Write a Main class with a main method. Assign 2 to int day. With switch (day) print "Monday" for case 1:, "Tuesday" for case 2:, "Unknown" for default:. Add break; after each case.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int day = 2;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            default:
                System.out.println("Unknown");
        }
    }
}

Expected output

Tuesday

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the switch concepts

Term Meaning
switch Selection
case Branch
break Exit
default Fallback

2 What does break do in a switch?

  • Starts a loop
  • Falls to next case
  • Nothing
  • Exits the switch Correct answer

Explanation: break exits the switch and continues after it.

3 Complete the case branch

Question
int day = 1;
switch (day) {
____ 1:
        System.out.println("Monday");
        break;
}
Answer
int day = 1;
switch (day) {
case 1:
        System.out.println("Monday");
        break;
}

Explanation: case 1: marks the first branch.

All lessons in Beginner