.


Divya

Java switch statement


In Java The switch statement is used to perform different actions based on multiple conditions.

Syntax:


switch (n)
{
    case label1:
        code to be executed if n=label1;
 
      break;
 
 
case label2:
        code to be executed if n=label2;
   
 
  break;
 
 
case label3:
        code to be executed if n=label3;
   
 
  break;
    ...
    default:
        code to be executed if n is different from all labels;
}

Example

class switch statement Example1 {
public static void main(String[] args) {
int a=30;
switch(a){
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
case 40: System.out.println("40");break;
default:System.out.println("Not in 20, 30 or 40");
}
}
}

Output : 30

Example

class switch statement Example2 {
public static void main(String[] args) {
int a=40;
switch(a){
case 20: System.out.println("20");
case 30: System.out.println("30");
case 40: System.out.println("40");
default:System.out.println("Not in 20, 30 or 40");
}
}
}
}

Output :
40
Not in 20, 30 or 40



.