Java fall through switch statements


 Following rules govern the fall through the behavior of switch statement.

  1. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

  2. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

  3. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

Following is an example

Live Demo

public class Test {

   public static void main(String args[]) {
      // char grade = args[0].charAt(0);
      char grade = 'C';

      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");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}

Compile and run the above program using various command line arguments. This will produce the following result −

Output

Well done
Your grade is C
raja
Published on 22-Jan-2018 07:08:18
Advertisements