switch Statement

A switch construct permits a variable to be tried for equity against a rundown of values. Each one value is known as a case, and the variable being exchanged on is checked for each one case. The syntax for using this decision making construct is as follows:

switch ( < condition > ) {
case value1: //Statements
  break;
case value2: //Statements
  break;
default:
  //Optional
}

The accompanying runs apply to a switch construct:

  • The variable utilized as a part of a switch explanation must be a short, byte, char or int.

  • You can have any number of case explanations inside a switch. Each one case is trailed by the value to be contrasted with and a colon.

  • The value for a case must be the same type as the variable in the switch and it must be a steady or an exacting value.

  • When the variable being exchanged on is equivalent to a case, the announcements after that case will execute until a break is arrived at.

  • When a break is arrived at, the switch ends, and the stream of control bounces to the following line after the switch.

  • Not each case needs to contain a break. In the event that no break shows up, the stream of control will fall through to consequent cases until a break is arrived at.

  • A switch articulation can have a discretionary default case, which must show up toward the end of the switch. The default case can be utilized for performing an undertaking when none of the cases is true. No break is required in the default case. However, as per the convention, the use of the same is recommended.

Sample Implementation:

public class myTest {
  public static void main(string args[]) {
    char mygrade = ‘A’;
    switch (mygrade) {
    case“ A”:
      System.out.println(“Excellent Performance!”);
      break;
    case“ B”:
      System.out.println(“Good Performance!”);
      break;
    default:
      System.out.println(“Failed”);
    }
  }
}

Aggregate and run above code utilizing different inputs to grade. 

This would create the accompanying result for the present value of mygrade:

Excellent Performance!