DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Switch Case

What is switch statment?

  • The switch keyword in Java is used to execute one block of code among many alternatives.

Syntax :
switch(expression){
case value1:
//code
break;
case value2:
//code
break;
...
...
default:
//default statment
}

  • The expression is evaluated once and compared with the values of each case.
  • If expression matches with value1, the code of case value1 are executed. Similarly, the code of case value2 is executed if expression matches with value2.
  • If there is no match, the code of the default case is executed.

What data types are supported in switch case expression?

  • byte, short, int, char, String

Why break statement is used?

  • The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed.

Example :
public class Sample {

public static void main(String[] args)
{
    char grade = 'B';
    switch(grade) {
        case 'A' :
            System.out.println("Excellent!");
            break;
      **  case 'B' :
        case 'C' :**
            System.out.println("Well done");
            break;
        case 'D' :
            System.out.println("You passed");
            break;
        case 'F' :
            System.out.println("Better try again");
            break;
        default :
            System.out.println("Invalid grade");
   }

}
Enter fullscreen mode Exit fullscreen mode

}

What is the syntax of Switch case supported in java 12 and above?

  • arrow (->) syntax.
  • No need to add break statement to each case statement.

Example:
int mark = 50;
switch (mark) {
case 90 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Faile";
};
System.out.println(dayName);
// Output: Wednesday

How to write multiple statement in a case block ?

int day = 1;
switch (day) {
case 1:
System.out.println("Monday");
System.out.println("Start of week");
System.out.println("Go to work");
break;

case 2:
    System.out.println("Tuesday");
    break;

default:
    System.out.println("Invalid day");
Enter fullscreen mode Exit fullscreen mode

}

Java 12:
case 1 -> {
System.out.println("Monday");
System.out.println("Start of week");
}

How to write mutiple cases with same statement?

switch(day) {
case 1:
case 7:
System.out.println("Holiday");
System.out.println("Enjoy!");
break;
}

Java 12:
case 1, 7 -> System.out.println("Weekend");

Top comments (0)