How to Use a Switch Case in Java
The switch statement is a powerful tool in Java, that allows you to execute one block of code among many alternative cases based on the output value of the condition. It’s a viable alternative to using multiple if-else statements to make our code more readable and efficient. It is a control statement that evaluates a variable and compares it to multiple cases. When a match is found, the corresponding block of code is executed. If no match is found, the default block (if defined) is executed. Let’s understand the switch statement and case, its syntax, and see multiple real-life examples to open our minds to its practical application.
Also Read : A Comprehensive Guide on the Basic For Loop in Java
switch(variable)
{
case variable value 1:
// Body of code
break;
case variable value 2:
{
// Body of code
break;
}
default:
// Body of code
}
Variable: The variable (or expression) inside the switch must be of the data types byte, short, char, int, String, or an enum.
Case: In every case block, the case keyword is followed by a value to be compared to and a colon. After the colon, the body of code is present, which contains the executable lines of code that should be executed if the control comes to that case. The body of code starts after the colon and the brackets are not mandatory.
Break: The break statement is written inside a case block and it is used to stop the execution of the switch case block. Without this, the program continues to the next case and goes on until the end of all the cases present.
Default: Default is a keyword in Java and the default block is executed if no values of the case match with the value of the switch variable. It’s not mandatory, but adding a default block is a good practice.
Problem Statement 1: Write a program to perform addition, multiplication, subtraction, and division using switch case.
Solution: To write a program to perform addition, multiplication, subtraction, and division using switch case, we first create an object of the ‘Scanner’ class and get the input in the run time (from the user’s output console). Then, we create an infinite for loop to execute the body of code repeatedly until the ‘break’ keyword is used to stop the loop.
We take two input values from the user of the double data type and use those values in the different cases we have created for the different mathematical operations. For the switch block’s variable (or expression), we get a value of the ‘char’ data type from the user using the ‘Scanner’ class. This ‘char’ value is obtained by the ‘charAt(int index)’ method of the ‘String’ class. When the user enters the String “add”, the char value at the first index position is obtained and used to determine which case should execute.
Using the ‘print(String a)’ and ‘println(String a) ’methods of the ‘PrintStream’ class we send the desired output in the output console to the user. Using the ‘close()’ method of the ‘Scanner’ class we close the scanner input. To end the for loop’s execution, we create a variable of int data type and increment it in case of an invalid response. Then, using an if block with the break keyword inside the loop body we can exit the loop.
package core_java;
import java.util.Scanner;
public class Switch_Case_Calculator {
public static void main(String[] args) {
System.out.println("Welcome to Grotechminds Calculator!");
Scanner Sc = new Scanner(System.in);
for( ; ; ) {
System.out.print("Enter first number: ");
double num1 = Sc.nextDouble();
System.out.print("Enter second number: ");
double num2 = Sc.nextDouble();
System.out.println("Enter an operation (add, sub, mul, div)");
char operator = Sc.next().charAt(0);
double result=0;int a=0;
switch (operator) {
case 'a':
result = num1 + num2;
break;
case 's':
result = num1 - num2;
break;
case 'm':
result = num1 * num2;
break;
case 'd':
result = num1 / num2;
break;
default:
{ System.out.println("Invalid operator");a++;}
}
if(a>0)
{
System.out.println("Session Ended.");
Sc.close();
break;}
System.out.println("The result is: " + result);
}
}
}
Problem Statement 2: Write a program to explain the meaning of the traffic lights with colours red, yellow and green using switch case.
Solution: To write a program to explain the meaning of the traffic lights with colours red, yellow, and green using switch case, we first create an object of the ‘Scanner’ class and get the input in the run time (from the user’s output console). Then, we create an infinite for loop to execute the body of code repeatedly until the ‘break’ keyword is used to stop the loop.
For the switch block’s variable (or expression), we take an input value from the user of the ‘String’ data type and use that value in the different cases we have created for the different coloured traffic lights using the ‘Scanner’ class. This ‘String’ value is obtained by the ‘next()’ method of the ‘Scanner class. When the user enters the String “Red”, it is matched with the various cases we have created, and the case that accepts “Red” will get the control and its body of code is executed. In the same way, depending upon the colour name given by the user, we can determine which case should execute.
Using the ‘println(String a) ’method of the ‘PrintStream’ class we send the desired output in the output console to the user. Using the ‘close()’ method of the ‘Scanner’ class we close the scanner input. To end the for loop’s execution, we create a variable of int data type and increment it in case of an invalid response. Then, using an if block with the break keyword inside the loop body we can exit the loop.
package core_java;
import java.util.Scanner;
public class Switch_Case_Traffic_Light {
public static void main(String[] args) {
Scanner Sc=new Scanner(System.in);
for( ; ; ) {
System.out.println("Enter a traffic signal colour"
+ " to know its meaning!");
int a=0;
String light_clr = Sc.next();
switch (light_clr)
{
case "Red":
System.out.println("Red means, Stop");
System.out.println("-----------------------");
break;
case "Yellow":
System.out.println("Yellow means, Caution");
System.out.println("-----------------------");
break;
case "Green":
System.out.println("Green means, Go");
System.out.println("-----------------------");
break;
default:
{System.out.println("Invalid light color");
System.out.println("-----------------------");
System.out.println("Session Ended!");
Sc.close(); a++;
break; }
}
if(a>0) {break;}}
}
}
Problem Statement 3: Write a program that simulates the vending machine billing mechanism using a switch case.
Solution: To write a program that simulates the vending machine billing mechanism using a switch case, we first create an object of the ‘Scanner’ class and get the input in the run time (from the user’s output console). Then, we create an infinite for loop to execute the body of code repeatedly until the ‘break’ keyword is used to stop the loop.
We take an input value from the user of the ‘int’ data type and use that value in the different cases we have created for the different food items available for selection. For the switch block’s variable (or expression), we get a value of the ‘int’ data type from the user using the ‘Scanner’ class. This ‘int value is obtained by the ‘nextInt()’ method of the ‘Scanner class. When the user enters the value “1”, it is matched with the various cases we have created, and the case that accepts “1” will get the control and its body of code is executed. In the same way, depending upon the food item number corresponding to its name which is given by the user, we can determine which case should execute.
Using the ‘print(String a)’ and ‘println(String a) ’methods of the ‘PrintStream’ class we send the desired output in the output console to the user. Using the ‘close()’ method of the ‘Scanner’ class we close the scanner input. To end the for loop’s execution, we create a variable of int data type and increment it in case of an invalid response. Then, using an if block with the break keyword inside the loop body we can exit the loop.
package core_java;
import java.util.Scanner;
public class Switch_Case_Vending_Machine {
public static void main(String[] args) {
System.out.println("Welcome to Grotechminds Vending Machine Menu:");
for( ; ; ) {
Scanner Sc = new Scanner(System.in);
System.out.println("Enter '1' for GTM Cookie - Rs. 50.00");
System.out.println("Enter '2' for GTM Chips - Rs. 30.00");
System.out.println("Enter '3' for GTM Chocolate - Rs.40.00");
System.out.print("Select an item (1-3): ");
int choice = Sc.nextInt(); int a=0;
switch (choice) {
case 1:
System.out.println("You selected Cookie. Please pay Rs. 50.00.");
System.out.println("---------------------------------------------");
break;
case 2:
System.out.println("You selected Chips. Please pay Rs. 30.00.");
System.out.println("---------------------------------------------");
break;
case 3:
System.out.println("You selected Chocolate. Please pay Rs. 40.00.");
System.out.println("---------------------------------------------");
break;
default:
{a++;
System.out.println("Invalid selection.");
Sc.close();
System.out.println("---------------------------------------------");
System.out.println("Session Ended! Thanks for shopping from GTM.");
break;} }
if(a>0) {break;}
}
}
}
In Java, ‘enum’ (short for “enumeration”) is a special data type that gives a variable an option to be a set of predefined constants. The enum can be used to, but not limited to represent a fixed set of constants like days of the week, directions, or any other data that can be categorized. Using enum with switch statements in Java improves the code readability and maintainability by allowing us to handle a fixed set of constants more efficiently. Let us look into the example below to understand it more clearly.
Problem Statement 4: Write a program to simulate the coffee shop POS billing machine software using a switch case.
Solution: To write a program to simulate the coffee shop POS billing machine software using a switch case, we first create a variable of ‘enum’ data type. Since the coffee size available in the shop is fixed and categorized, it gives us an opportunity to use the ‘enum’ data type and understand its implications.
Inside the enum body, we declare a set of values to the variable. We create a variable of double data type inside the enum body to store the double value present in the enum variable. We then create a constructor of the enum to fetch the double value associated with the set of variable values of the enum type. ‘CoffeeSize’ is an enum that represents different sizes of coffee (‘SMALL’, ‘MEDIUM’, ‘LARGE’). Each enum constant (‘SMALL’, ‘MEDIUM’, ‘LARGE’) has a corresponding price field (‘30.00’, ‘50.00’, ‘70.00’) respectively initialized in its constructor.
Each enum constant (‘SMALL’, ‘MEDIUM’, ‘LARGE’) has a constructor that takes a double parameter (‘price’) to initialize its price field. (e.g.,) SMALL(30.00) initializes SMALL.price to 30.00. When the user inputs a valid size (‘SMALL’, ‘MEDIUM’, ‘LARGE’), the static method inside the enum body, CoffeeSize.fromString(input) is called to convert the input into the corresponding enum constant (size) using switch case. The user’s input of the ‘String’ value, obtained from the ‘next()’ method of the ‘Scanner’ class is matched with the values of the various cases and that case body which is matched is executed.
After obtaining size, the program directly accesses ‘size.price’ to retrieve the price associated with that enum constant. In the main method, an object of the ‘Scanner’ class is used to get the input in the run time (from the user’s output console). Then, we create an infinite while loop to execute the body of code repeatedly until the ‘exit keyword is used to exit from the program.
Using the ‘print(String a)’ and ‘println(String a) ’methods of the ‘PrintStream’ class we send the desired output in the output console to the user. Using the ‘close()’ method of the ‘Scanner’ class we close the scanner input. To end the for loop’s execution, we create a variable of int data type and increment it in case of an invalid response. Then, using an if block with the break keyword inside the loop body we can exit the loop.
Also Read:
Understanding the ‘throw’ and ‘throws’ keywords in Java
package core_java;
import java.util.Scanner;
public class Switch_Case_Enum {
enum CoffeeSize {
SMALL(30.00), MEDIUM(50.00), LARGE(70.00);
public double price;
CoffeeSize(double price) {
this.price = price;
}
public static CoffeeSize fromString(String size) {
switch (size.toUpperCase()) {
case "SMALL":
return SMALL;
case "MEDIUM":
return MEDIUM;
case "LARGE":
return LARGE;
default:
return null;
}
}
}
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
System.out.println("Welcome to Grotechminds Coffee Shop Simulator!");
System.out.println("-------------------------------------------------------");
while (true) {
System.out.println("Enter coffee size (SMALL, MEDIUM, LARGE) or 'exit' to quit:");
String input = Sc.next();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Thank you for visiting Grotechminds Coffee Shop Simulator!");
break;}
CoffeeSize size = CoffeeSize.fromString(input);
if (size != null) {
System.out.println("The price of a " + size + " coffee is Rs. " + size.price);
System.out.println("-------------------------------------------------------");}
else {
System.out.println("Invalid coffee size entered. Please try again.");
System.out.println("-------------------------------------------------------");}
}
Sc.close();
} }
The switch case is a versatile and powerful control statement in Java, that can simplify complex conditional logic. It comes in handy when we need to execute one of many possible blocks of code based on a variable’s value. Remember to practice, stay updated with the latest trends in Automation Software Testing Course,and maintain a positive attitude throughout your interview process. Even though it can only handle certain types of data (‘byte’, ‘short’, ‘char’, ‘int’, ‘String’, and ‘enum’), the switch case statement proves to be an essential tool for us, demonstrated with the help of the previous examples.
Also read:
Consult Us