Lesson 14 +10 XP

Java Switch

Java Switch

The switch statement picks one of many code blocks to run. It is a cleaner way to test a value against many cases.

Switch syntax

int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  default:
    System.out.println("Looking forward to the weekend");
}

How it works

  • The switch expression is evaluated once.
  • It is compared to each case.
  • When a match is found, that block runs until a break.
  • default runs when no case matches.

The break keyword

break stops the switch from running the remaining cases. Without break, Java keeps running the next case (this is called fall through).

Default

The default block is optional. It is the fallback when no case matches.

TL;DR

  • switch tests one value against multiple case labels.
  • Each case should end with break.
  • default runs when no case matches.