Java - Switch case
Q1. How can a switch statement be used in Java to implement menu-based selection ?
A switch statement in Java is used to execute one block of code from multiple options based on the value of a variable. It is especially useful for menu-driven programs where a user selects an option using numbers or predefined values.
Example: Menu Selection Using switch
Explanation
How Valid and Invalid Inputs Are Handled
Example: Menu Selection Using switch
public class FoodMenu {
public static void main(String[] args) {
int choice = 3; // User selection
switch (choice) { case 1: System.out.println("You selected Pizza."); break;
case 2: System.out.println("You selected Burger."); break;
case 3: System.out.println("You selected Pasta."); break;
case 4: System.out.println("You selected Salad."); break;
default: System.out.println("Invalid selection."); } }}Explanation
- The switch statement evaluates the value of choice.
- Each case represents a valid menu option.
- The break statement prevents fall-through to the next case.
- The default case executes when the input does not match any valid option.
How Valid and Invalid Inputs Are Handled
- Valid inputs (1–4) trigger the corresponding menu item.
- Any other value triggers the default block, displaying an error message.
- This ensures controlled and predictable program flow.