Java Switch

Instead of writing many if..else statements, you can use the switch statement.

In Java programming, the switch statement offers a streamlined way to execute one out of multiple code blocks, providing an alternative to using numerous if..else statements.



The switch statement selects one of many code blocks to be executed:

Syntax

switch(expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // code block
}




This is how it works:

  1. The switch expression is evaluated once.
  2. The result is compared with the values of each case.
  3. If a match is found, the corresponding code block is executed.
  4. The break and default keywords are optional and will be described later.

The example below uses the weekday number to calculate the weekday name:

Example:

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;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)




The break Keyword

When Java reaches a break keyword, it exits the switch block. This stops further execution and case testing inside the block. The break statement saves execution time by ensuring that no additional cases are evaluated once a match is found.




The default Keyword

The default keyword specifies a block of code to run if there is no match with any case value:

Example:

int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the weekend");
}
// Outputs "Looking forward to the weekend"

Note that if the default statement is used as the last statement in a switch block, it does not need a break.

Scroll to Top