Switch case statement

Switch case statement is used when we have number of options (or choices) and we may need to perform a different task for each choice.
The syntax of Switch case-

switch (variable or an integer expression)
{
     case constant:
     //Java code
     ;
     case constant:
     //Java code
     ;
     default:
     //Java code
     ;
}
 

A Simple Switch Case Example

public class SwitchCaseExample1 {

   public static void main(String args[]){
     int num=2;
     switch(num+2)
     {
        case 1:
   System.out.println("Case1: Value is: "+num);
 case 2:
   System.out.println("Case2: Value is: "+num);
 case 3:
   System.out.println("Case3: Value is: "+num);
        default:
   System.out.println("Default: Value is: "+num);
      }
   }
}

Output:

Default: Value is: 2
 

Example with break statement

public class SwitchCaseExample2 {

   public static void main(String args[]){
      int i=2;
      switch(i)
      {
  case 1:
    System.out.println("Case1 ");
    break;
  case 2:
    System.out.println("Case2 ");
    break;
  case 3:
    System.out.println("Case3 ");
    break;
  case 4:
           System.out.println("Case4 ");
           break;
  default:
    System.out.println("Default ");
      }
   }
}

Output:

Case2

error: Content is protected !!