Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Switch

Java Switch Statements

Rather than employing numerous if…else statements, you can utilize the switch statement.

This statement chooses one of several code blocks to execut:

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Here’s how it operates:

  1. The switch expression undergoes evaluation once.
  2. It compares the value of the expression with each case’s values.
  3. Upon finding a match, the corresponding block of code executes.
  4. The keywords break and default are optional and will be further explained later in this chapter.

The following example utilizes the weekday number to determine 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

Upon encountering a break keyword in Java, the program exits the switch block.

This will halting the execution of further code and case testing within the block.

Once a match is found and the task is completed, it’s time to implement a break. Further testing is unnecessary at this point.

A break can significantly save execution time by effectively bypassing the execution of all remaining code within the switch block.

The default Keyword

The default keyword designates a piece of code to execute if there is no match with any case.

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"

 

If the default statement is positioned at the end of a switch block, a break statement is unnecessary.