Loading

Interview Questions of switch-case

Scenario 1: Using Switch Statement for Menu Selection

Scenario:

You are building a simple console-based food ordering application. When a user enters a number (1 to 4), the system should display the selected menu item. If the user enters any other number, the system should display "Invalid selection."

  • Pizza
  • Burger
  • Pasta
  • Salad


Question:

How would you implement this menu selection logic using a switch statement in Java? Please write a code snippet and explain how your solution handles both valid and invalid inputs.


Answer:

public class FoodMenu {
    public static void main(String[] args) {
        int choice = 3; // Example user input
        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 checks the users choice.
  • Each case corresponds to a menu item.
  • The default case handles any input that does not match the menu options, ensuring the program responds gracefully to invalid selections.