Switch Statement


Switch statements are almost similar to the if-else-if ladder control statements in Java. It is a multi-branch statement. It is a bit easier than the if-else-if ladder and also more user-friendly and readable. The switch statements have an expression and based on the output of the expression, one or more blocks of codes are executed. These blocks are called cases. We may also provide a default block of code that can be executed when none of the cases are matched similar to the else block.

Syntax:

switch (expression) {

  case value1:

      //code block of case with value1

      break;

  case value2:

      //code block of case with value2

      break;

  .

  .

  case valueN:

      //code block of case with valueN

      break;

  default:

     //code block of default value

}

There are certain points that one needs to be remembered while using switch statements:

The expression can be of type String, short, byte, int, char, or an enumeration.

We cannot have any duplicate case values.

The default statement is optional.

Usually, the break statement is used inside the switch to terminate a statement sequence.

The break statement is optional. If we do not provide a break statement, the following blocks will be executed irrespective of the case value. This is known as the trailing case.

Example-

public class SwitchCaseConcept {

               public static void main(String[] args) {

                              int n1 = 20, n2 = 10, result;

                              int ch = 3;

                              switch (ch) {

                              case 1:

                                             result = n1 + n2;

                                             System.out.println("\n Addition Result: " + result);

                                             break;

 

                              case 2:

                                             result = n1 - n2;

                                             System.out.println("\n Substraction Result: " + result);

                                             break;

 

                              case 3:

                                             result = n1 * n2;

                                             System.out.println("\n Multiplication Result: " + result);

                                             break;

 

                              case 4:

                                             result = n1 / n2;

                                             System.out.println("\n Division Result: " + result);

                                             break;

 

                              default:

                                             System.out.println("Invalid Choice");

                                             break;

                              }

               }

}

Output:

Multiplication Result: 200