What Is Java Switch Statement?

Introduction to Java Switch

In Java, the switch statement is a control flow tool that is used to make decisions based on the value of a single variable or expression.

It provides a clean and organized way to test multiple possible outcomes without writing several if…else if statements.

When you have one variable that can take many possible values, such as a grade, a day of the week, or a menu choice, the switch statement helps you choose which block of code to run, based on that value.

In simple terms, instead of checking the same variable again and again in multiple if statements,
You can write it once in a switch and list different cases for each possible value.

Syntax of Switch Statement

switch (expression) {
case value1:
// Code runs if expression == value1
break;

case value2:
// Code runs if expression == value2
break;

default:
// Code runs if no case matches
}

How It Works?

  • The expression inside the switch is evaluated once.
  • Java then compares that value with each case label.
  • When a match is found, the code under that case runs.
  • The break keyword is used to stop the switch from checking further cases.
  • If no case matches, the default block executes (if it exists).

What is Expression in Java?

In Java, an expression is any valid combination of variables, constants, operators, and method calls that produces a single value. You can think of an expression as a small piece of code that answers.

For example: 5 + 3 adds two numbers that will give a result of 8.

In a switch statement, the expression is what Java checks to decide which case to run.
It’s written inside the parentheses of switch().

Example of Switch Statement with Number

public class SwitchIntro {
public static void main(String[] args) {
int day = 3;

switch (day) { // <-- 'day' is the expression here
case 1:
System.out.println("Today is Monday");
break;

case 2:
System.out.println("Today is Tuesday");
break;

case 3:
System.out.println("Today is Wednesday");
break;

default:
System.out.println("Invalid day number");
}
}
}

Output:

Today is Wednesday

Example 2: Switch with Strings

public class SwitchStringExample {
public static void main(String[] args) {
String fruit = "Apple";

switch (fruit) {
case "Apple":
System.out.println("Apples are red or green.");
break;
case "Banana":
System.out.println("Bananas are yellow.");
break;
case "Orange":
System.out.println("Oranges are orange.");
break;
default:
System.out.println("Unknown fruit.");
break;
}
}
}

Output:

Apples are red or green.

Example 3: Switch Without Break

If you don’t write a break statement after each case, Java doesn’t stop after a match.
It continues to run the following cases, even if they don’t match.

Example:

public class SwitchWithoutBreak {
public static void main(String[] args) {
int number = 2;

switch (number) {
case 1:
System.out.println("You selected One");
case 2:
System.out.println("You selected Two");
case 3:
System.out.println("You selected Three");
default:
System.out.println("End of switch.");
}
}
}

Output:

You selected Two
You selected Three
End of switch.

It means:

  • The switch finds the match at case 2.
  • However, since there is no break, Java continues to execute the next cases (3 and default) as well.

What is a Nested Switch in Java?

A nested switch is when you put one switch statement inside another switch. This is useful when you need to make decisions on multiple levels. For example, first check a department, then check the year of study.

Example: College Courses and Year

public class NestedSwitchNumberExample {
public static void main(String[] args) {
String course = "Science";
int year = 2;

switch (course) {
case "Science":
switch (year) {
case 1:
System.out.println("Welcome to 1st year of Science.");
break;
case 2:
System.out.println("You are in 2nd year of Science.");
break;
case 3:
System.out.println("You are in 3rd year of Science.");
break;
default:
System.out.println("Science: Year not recognized.");
break;
}
break;

case "Arts":
switch (year) {
case 1:
System.out.println("Welcome to 1st year of Arts.");
break;
case 2:
System.out.println("You are in 2nd year of Arts.");
break;
default:
System.out.println("Arts: Year not recognized.");
break;
}
break;

default:
System.out.println("Unknown Course.");
break;
}
}
}

Output:

You are in 2nd year of Science.

In this code:

  • The outer switch checks the course type (Science or Arts).
  • Since the course is “Science”, it goes inside that case.
  • The inner switch then checks the year.
  • It finds year = 2 and prints the corresponding message.

Advantages of Switch Statement

  1. Improved Readability:
    • When you have multiple conditions based on the same variable, a switch makes the code cleaner and more organized.
    • Each case is clearly separated, which makes it easier for others to read and understand.
  2. Efficient Execution:
    • Java optimizes switch statements at the bytecode level, so checking multiple fixed values can be faster than using a long chain of if…else if.
  3. Easy to Debug:
    • The structured format of the switch makes it simpler to trace the program flow.

Disadvantages of Switch Statement

  1. Limited Data Types:
    • Switch works only with certain types: int, char, byte, short, String, and enum.
    • You cannot directly use Boolean, float, double, or complex conditions.
  2. Risk of Fall-Through:
    • If you forget the break statement, Java continues executing the next cases unintentionally. This can lead to unexpected results if not handled carefully.
  3. Not Flexible:
    • Switch cannot handle conditions like ranges (x > 5 && x < 10) or multiple expressions.
    • For such cases, if…else is more suitable.

Exercise: Menu Selection Using Switch

Create a Java program that simulates a small cafe menu. The program should display options for drinks and allow the user to select a drink by entering a number.

Use a switch statement to print the name of the drink and its price. Include a default case for invalid selections.

Menu:

  1. Coffee — ₹50
  2. Tea — ₹30
  3. Juice — ₹40
  4. Water — ₹10

Requirements:

  • Use a switch statement to handle user input.
  • Print a message like “You selected Coffee. Price: ₹50” for each valid selection.
  • Print “Invalid selection. Please choose a valid menu number.” for any number not on the menu.

Solution of this exercise

import java.util.Scanner;

public class CafeMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Cafe! Choose your drink:");
System.out.println("1. Coffee");
System.out.println("2. Tea");
System.out.println("3. Juice");
System.out.println("4. Water");

System.out.print("Enter the number of your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("You selected Coffee. Price: ₹50");
break;
case 2:
System.out.println("You selected Tea. Price: ₹30");
break;
case 3:
System.out.println("You selected Juice. Price: ₹40");
break;
case 4:
System.out.println("You selected Water. Price: ₹10");
break;
default:
System.out.println("Invalid selection. Please choose a valid menu number.");
}

scanner.close();
}
}

Sample Output (if user enters 3):

You selected Juice. Price: ₹40

Also Learn Important Topics of Java

Leave a Comment