Java Switch Statement -

Java Switch Statement

The switch statement in Java is a control structure that lets you execute a block of code among multiple options. It is a cleaner alternative to multiple if-else-if conditions, making your code more readable and efficient.


Syntax of Switch Statement

switch (expression) {
    case value1:
        // Code block for case 1
        break;
    case value2:
        // Code block for case 2
        break;
    // Add more cases as needed
    default:
        // Code block if none of the cases match
}
  • expression: The value being tested (integer, string, or enum type).
  • case value: A possible value for the expression.
  • break: Stops the execution of the switch block.
  • default: Executes if no cases match.

Example 1: Basic Switch Statement

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

        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            default:
                System.out.println("Weekend");
        }
    }
}

Output:

Wednesday

Real-Life Example: Grade System

public class GradeSystem {
    public static void main(String[] args) {
        char grade = 'B';

        switch (grade) {
            case 'A':
                System.out.println("Excellent!");
                break;
            case 'B':
                System.out.println("Well done!");
                break;
            case 'C':
                System.out.println("Good effort!");
                break;
            case 'D':
                System.out.println("You passed.");
                break;
            default:
                System.out.println("Invalid grade.");
        }
    }
}

Output:

Well done!

Switch Without Break

If you omit the break statement, all cases after the matching one will execute until a break or the end of the switch block.

Example 3: Fall-Through Behavior

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");
            default:
                System.out.println("Other number");
        }
    }
}

Output:

Two
Three
Other number

Solution: Use break

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

        switch (number) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("Three");
                break;
            default:
                System.out.println("Other number");
        }
    }
}

Output:

Two

Nested Switch

You can use a switch inside another switch for complex decision-making.

Example 4: Nested Switch Example

public class NestedSwitch {
    public static void main(String[] args) {
        String department = "Engineering";
        int year = 3;

        switch (department) {
            case "Engineering":
                switch (year) {
                    case 1:
                        System.out.println("Engineering, First Year");
                        break;
                    case 2:
                        System.out.println("Engineering, Second Year");
                        break;
                    case 3:
                        System.out.println("Engineering, Third Year");
                        break;
                }
                break;
            case "Arts":
                System.out.println("Arts Department");
                break;
            default:
                System.out.println("Invalid department.");
        }
    }
}

Output:

Engineering, Third Year

Switch with Strings

Since Java 7, switch supports strings, which improves flexibility.

Example 5: String-Based Switch

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

        switch (fruit) {
            case "Apple":
                System.out.println("It's red!");
                break;
            case "Banana":
                System.out.println("It's yellow!");
                break;
            case "Grapes":
                System.out.println("They're green or purple!");
                break;
            default:
                System.out.println("Unknown fruit.");
        }
    }
}

Output:

It's red!

Switch vs. If-Else

FeatureSwitchIf-Else
ReadabilityEasier with multiple conditionsComplex for many conditions
Data Types SupportedLimited (int, char, String, enums)Supports all data types
PerformanceFaster for many conditionsSlower due to multiple evaluations

Real-Life Example: Menu-Driven Program

import java.util.Scanner;

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

        System.out.println("Menu:");
        System.out.println("1. Add");
        System.out.println("2. Subtract");
        System.out.println("3. Multiply");
        System.out.println("4. Divide");
        System.out.println("Choose an option:");

        int choice = sc.nextInt();
        System.out.println("Enter two numbers:");
        int a = sc.nextInt();
        int b = sc.nextInt();

        switch (choice) {
            case 1:
                System.out.println("Result: " + (a + b));
                break;
            case 2:
                System.out.println("Result: " + (a - b));
                break;
            case 3:
                System.out.println("Result: " + (a * b));
                break;
            case 4:
                System.out.println("Result: " + (a / b));
                break;
            default:
                System.out.println("Invalid choice.");
        }

        sc.close();
    }
}

Output Example:

Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
Choose an option:
3
Enter two numbers:
6
7
Result: 42

By mastering the switch statement, you can simplify decision-making in your Java programs, making them cleaner and more efficient.

Leave a Comment