Java Switch

The switch statement selects one of many code blocks to be executed. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched.

Syntax : 

switch(expression) {
   case value1 :
      // code blocks to be executed.
      break; // optional
   
   case value2 :
      // code blocks to be executed.
      break; // optional
   
   // You can have any number of case statements.
   default : // Optional
      // code blocks to be executed.
}

 

The switch statement will be worded as below.

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the block of code inside case is executed.
  • The break and default keywords are optional. Break statement terminates the switch block when the condition is satisfied.
    It is optional. if not used, then next case is executed.

Example :

public class Aryatechno {
public static void main(String args[]) {
char grade = 'D';

switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Well done!");
break;
case 'C' :
System.out.println("Good!");
break;
case 'D' :
System.out.println("You passed!");
break;
case 'F' :
System.out.println("Failed Try again!");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Output :

You passed!
Your grade is D

Comments

Leave a Reply

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

85591