loading

Java Switch

Java Switch Statements

Use the switch statement to avoid writing numerous if..else statements.

One of several code blocks is chosen by the switch statement to be executed:

Syntax

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

Here’s how it functions:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • The break and default keywords are optional, and will be described later in this chapter

The weekday name is determined by using the weekday number in the following example:

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

Java exits the switch block when it comes across the break keyword.

This will put an end to case testing and additional code execution within the block.

After a match is made and the task is completed, a break is in order. Further testing is not required.

Because a break “ignores” the execution of the remaining code in the switch block, it can save a significant amount of execution time.

The default Keyword

If there is no case match, the default keyword indicates what code should be executed:

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"
				
			

It should be noted that a switch block does not require a break if the default statement is used as the final statement.

Share this Doc

Java Switch

Or copy link

Explore Topic