Switch Case Example Java Program

0

switch statement is very similar to if-else-if ladder statement.We can use switch statement to executes one statement from multiple condition. switch statement supports byte,short,int,long, enum types.Since java 7 String and some other wrapper type also support.




Points to remember for using switch statement

  • We can have any number of case values for a switch expression
  • It does not allow variables, the case value must be literal or constant
  • case value must be unique
  • Can have break statement which is optional, When controls reach to the break statement control will be terminated, If there is no break statement it will execute next case
  • The case value can have a default label which is optional

 

 import java.util.Scanner;

 public class SwitchCase
 {

 public static void main(String []args){

 Scanner user_input = new Scanner(System.in);
 System.out.println("Enter a number between 1 to 5");
 int number = user_input.nextInt();

 switch(number){
 case 1: System.out.println("You enter : One");
 break;
 case 2: System.out.println("You enter : Two");
 break;
 case 3: System.out.println("You enter : Three");
 break;
 case 4: System.out.println("You enter : Four");
 break;
 case 5: System.out.println("You enter : Five");
 break;
 default: System.out.println("You entered Invalid number Please enter between 1 to 5");
  }
 }
}


Output

Enter a number between 1 to 5
4
You enter : Four

Explanation:

Here our program accepts one int value which is a number, the switch case checks the corresponding case value if the case value matches with the number it prints the appropriative statements.

switch case using String


 import java.util.Scanner;

 public class SwitchString{
 public static void main(String[] args) {

 System.out.println("Enter your favourit  game");
 System.out.println("Cricket");
 System.out.println("Hockey");
 System.out.println("Vollyball");
 System.out.println("Football");

 Scanner enterGame = new Scanner(System.in);

 String game= enterGame.nextLine();

 switch(game){
 case "Cricket": System.out.println("Your favourite game is Cricket");
 break;

 case "Hockey": System.out.println("Your favourite game is Hockey");
 break;

 case "VollyBall": System.out.println("Your favourite game is VollyBall");
 break;

 case "Football": System.out.println("Your favourite gmae is FootBall");
 break;

 default: System.out.println("Enter valid game");
  }

  }
 }


Output

Enter your favorite game
Cricket
Hockey
volleyball
Football
Cricket
Your favorite game is Cricket

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !