Java Switch Keyword

Java Switch Keyword


Switch Keyword In Java 
It is also another conditional construct that control the flow of the program. It is used to check a variable for multiple constant values.
switch is a keyword in java, hence it will be in small case
if _ else is used to all types of comparison where as switch_ case is used to equal comparisons.
Syntax -
 
switch(variable){
case constant1:
statement1;
statement2;
statement3;
statement4;
// n number of statements ....

                  break;
case constant2:
statement1;
statement2;
statement3;
statement4;
break;

default:
              statement1;
statement2;
statement3;
statement4;
  }
 
Variable here is an expression that produces an integral value. The switch compares the result of the variable to each case value. If it finds a match, the corresponding statement (a single statement or multiple statements; braces are not required) executes. If no match occurs, the default statement executes.
Note -
1. switch, case, default, and break are keywords.
2. Switch expression evaluates only once .
Example -
Here’s an example that creates letters randomly and determines whether they’re vowels or consonants - 
 
import java.util.*;
public class VowelsAndConsonants { public static void main(String[] args) {
int dayno;
System.out.println("Input Day No : ");
Scanner ob = new Scanner(System.in);
dayno = ob.nextInt();
  switch(dayno)
  {
case 1:
      System.out.println("Monday);
      break;
case 2:
      System.out.println("Tuesday ");
      break;
case 3:
      System.out.println("Wednesday ");
      break;
case 4:
      System.out.println("Thursday");
      break;
case 5:
      System.out.println("Friday ");
      break;
case 6:
  System.out.println("Saturday ");
      break;
case 7:
      System.out.println("Sunday ");
      break;
default:
      System.out.println("Invalid day number. \nPlease try again ....");
      break;
      }
}

Output-
Input Day No : 4                                                                                             
Thursday