switch case statement in java with examples

0

switch case statement is another way for conditional statements , it can be a replacement of if else in some cases,

All Contributions

using switch statement, write java program to check if student is pass or fail, depending on his mark(mark is outof 10)

 System.out.println("enter your quiz mark:");
      int quiz=in.nextInt();
      switch(quiz)
      {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
              System.out.println("fail");
              break;
          case 6:
          case 7:
          case 8:
          case 9:
          case 10:
              System.out.println("pass");
          default: System.out.println("invalid entry");
      }



  //the same previous example but using if else
     Scanner input=new Scanner(System.in);
     System.out.println("enter the mark");
     int mark=input.nextInt();
     if(mark>=6 && mark<=10)
        System.out.println("PASS");
     else if(mark>=0 && mark<6)
         System.out.println("fail");
     else {
         System.out.println("invaild");
          }

write java program to enter week day number and print wether this day is weekday of weekend

Scanner input=new Scanner(System.in);
System.out.println("enter week day number:");
int daynumber=input.nextInt();
switch(daynumber) {
case 2:
case 3:
case 4:
case 5:
case 6:
 System.out.println("weekday");
 break;
case 1:
case 7:
 System.out.println("weekend");
 break;
default:
 System.out.println("invalid entry");
}

example of switch statement in java:

program reads number of week day, then prints the equavalent day name.

//write java program that ask user to enter the number of week day and
        //prints the equiavalent week day name
        System.out.println("enter the day number:");
        int daynumber=in.nextInt();
switch(daynumber)
      {
          case 1:
              System.out.println("saturday");
              break;
          case 2:
              System.out.println("sunday");
              break;
          case 3:
              System.out.println("monday");
              break;
          case 4: 
              System.out.println("tuesday");
              break;
          case 5:
              System.out.println("wednsday");
              break;
          case 6:
              System.out.println("thursday");
              break;
          case 7:
              System.out.println("friday");
              break;
          default:
              System.out.println("invalide entry");
      }

total contributions (3)

New to examplegeek.com?

Join us