Java Switch Statement (Beginner Friendly + Practical Examples)

βœ… What is a Switch Statement?

The switch statement in Java is a type of control flow statement used to execute one block of code out of many based on the value of a given expression. It’s commonly used as a cleaner alternative to multiple if-else-if statements when you are comparing the same variable with different constant values.

Using switch improves code readability and reduces complexity when you need to make a decision among several fixed options.


🧠 Syntax of Switch Statement

switch (expression) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
...
default:
// Code block if none of the cases match
}

πŸ“ Key Points:

  • The expression must be of type byte, short, int, char, String, or enum.

  • Each case is followed by a colon : and a block of code to execute.

  • The break keyword stops the execution from continuing to the next case.

  • If break is not used, Java performs fall-through to the next case.

  • The default block is optional and is executed when no other case matches.


🎯 Example 1: Simple Switch with Integers

public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println(“Sunday”);
break;
case 2:
System.out.println(“Monday”);
break;
case 3:
System.out.println(“Tuesday”);
break;
default:
System.out.println(“Invalid day”);
}
}
}

Output:

Tuesday

🎯 Example 2: Switch with String

public class SwitchStringExample {
public static void main(String[] args) {
String fruit = "Mango";
switch (fruit) {
case “Apple”:
System.out.println(“It is an Apple”);
break;
case “Mango”:
System.out.println(“It is a Mango”);
break;
case “Banana”:
System.out.println(“It is a Banana”);
break;
default:
System.out.println(“Unknown fruit”);
}
}
}

Output:

It is a Mango

⚠️ Fall-Through Behavior

If you forget to use break, Java will continue to execute all the following cases, even if they don’t match.

public class FallThroughExample {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
System.out.println(“One”);
case 2:
System.out.println(“Two”);
case 3:
System.out.println(“Three”);
}
}
}

Output:

Two
Three

Explanation:
Since there is no break after case 2, Java continues to execute case 3 as well. This is called fall-through, and it’s something to be cautious about.


βœ… When to Use Switch

  • When comparing a single variable against several constant values.

  • When you want cleaner code than multiple if-else-if blocks.

  • When readability and structure matter, especially for large sets of conditions.

  • When working with fixed values like menu choices, days of the week, or status codes.

Related Posts