Translate

Switch statement in Java.

Switch statement in Java

  • Switch statement allows us to execute one statement from many statement and the statements are called case.
  • Inside the body of switch there are a number of cases and there is a single number is passed at the place of parameter to select and execute a case.
 
  • In the switch statement a value/number is passed in the place of parameter and the case from which the parameter is matched is executed.
  • If no case matched with parameter then default case will execute.
class Easy
{
 public static void main(String[] args) 
 {
  int day=2;
  switch(day)
  {
   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("Thrusday");
    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("No case matched");
  }
 }
}
/*
### Output ###
Tuesday
because day is equal to 2 and it matches with
case 2 so the output is Tuesday
*/
import java.util.Scanner;
class Easy
{
 public static void main(String[] args) 
 {
  Scanner in=new Scanner(System.in);
  char ch;
  System.out.println("Enter any alphabet");
  ch=in.next().charAt(0);
  switch(ch)
  {
   case 'a':
   case 'e':
   case 'i':
   case 'o':
   case 'u':
    System.out.println("Vowel");
    break;
   default:
    System.out.println("Consonent");
  }
 }
}
/*
### Output ###
Enter any alphabet
m
Consonent
*/
Next Post Previous Post
No Comment
Add Comment
comment url