Java Tutorial-Java Switch

Java Switch

 

Java Switch Statements


The switch statements are used to select one of many code blocks to be executed.


Syntax

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

This is how it works:


  • The switch expression is evaluated once.
  • The value of the expression is compared to the value in each case.
  •  If the value is matched, the block of code is executed.
  • The break and default keywords are optional. Without these keywords, still we can write code for different functionalities.

The break keyword


When the case block reaches the break statement, it breaks out of the switch statement. There are various options in cases, once the case gets matched, the block of code gets executed and the break statement brings to the end of the switch statement. This break statement could save lot of execution time because it “ignores” the rest of code in the switch block.

 

The default keyword


This specifies some code to run if there is no case match. This is default block is preferably used as the last statement in the switch block and it does not need a break statement.

 

Example

int day = 3;
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;
default:
       System.out.println("Not a valid day");
}

Output

Wednesday