Sun. Dec 22nd, 2024

The switch statement can be used for executing a group of statements based on a value.

Syntax

switch(argument){
  case label1: statement1;
               break;
  case label2: statements2;
               break;
  default: default statements;
}

Program5:

class SwicthDemo{
   public static void main( String[] args){
   int ch=2;
 swicth(ch){
   case1: System.out.println("First choice");
            break;
case2: System.out.println("Second choice");
            break;
case3: System.out.println("Third choice");
            break;
case4: System.out.println("Fourth choice");
            break;
default:  System.out.println("wrong Choice");
     }
  }
}

Rule1: Specifying the arguments to switch statement is mandatory and it should be either byte, short, int or char only.

Rule2: Specifying the flower braces to switch statement is mandatory.

Rule3: Specifying the case default statements in switch is optional.

Rule4: A switch statement can contain any number of cases and it can contain at most one default.

Rule5: The default statement can be specified anywhere in the switch statement.

Rule6: The case labels must be unique i.e. they should not be empty and they should not duplicated.

Rule7: Specifying the break statement is optional. The break is a transfer statement and it will transfer the control from inside the switch to outside the switch, so that it skips the execution of remaining cases.

Rule8: When a switch statement is executed, switch argument is compared with case labels and execution will begin from case onwards whose labels is matching with the argument and continues until it encounters a break statement or until the end of switch.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *