Java Switch Statement

As we know about if-else and if...else...if ladder in java

Remember: in if-else or if...else...if ladder we execute a block of code on the specific condition.

But there was a problem if...else...if ladder is suitable for only less number of the code block.

For large no of condition and code block, we use a switch case statement

Let’s know about switch case:

In the switch statement, we check the value of variable or expressions

then on the base of value and expression, we execute different part of code-block

Let’s see syntax of switch statement:

switch (variable/expression) {
case value1:
   // statements
   break;
case value2:
   // statements
   break;
   .. .. ...
   .. .. ...
default:
   // statements
}

Now let’s see working of switch statement with example:

In switch case first we pass variable or expression in switch

Switch (variable/expression)
   {

   }

Then in the body of the switch statement, we write different case

Example:

switch (variable/expression) {
    case value1:
          // statements
           break;

   case value2:
          // statements
         break;

}

Then we match the value of the expression with each case

Suppose the variable/expression is equal to value 2, in this case, all states of that matching case is executed

Notice, the use of break statement this statement terminates the execution of switch statement

The break statement is important because if they are used

All statements after the matching case label are executed in sequence until the end of the switch statement met.

Last thing:
If no any case matches then default case will execute

 switch (variable/expression) {
default:
   // statements
}

Diagram of a switch statement:

Switch Statement in Java -flow chart

Note: – switch statement in java only work with

  • Primitive data type byte, short, char, int
  • Enumerated type (java enums)
  • String class
  • A few that wrap primitive type of character, byte, short, and Integer

Example if switch statement:

class Day {
   public static void main(String[] args) {

      int week = 4;
      String day;
	        
      switch (week) {
         case 1:
           day = "Sunday";
           break;
         case 2:
           day = "Monday";
	   break;
         case 3:
           day = "Tuesday";
           break;
         case 4:
           day = "Wednesday";
           break;
         case 5:
           day = "Thursday";
           break;
         case 6:
           day = "Friday";
           break;
         case 7:
           day = "Saturday";
           break;
         default: 
           day = "Invalid day";
           break;
      }
      System.out.println(day);
   }
}

When you run the program, the output will be:

Wednesday



SHARE THIS PAGE





Important Link