HOME HTML EDITOR C JAVA PHP

Java Switch: Multi-Way Branching

Instead of writing many if..else statements, you can use the switch statement. It selects one of many code blocks to be executed based on a single value.

Critical Tip: Don't forget the break keyword! Without it, Java will continue executing the next case regardless of the value (this is called "fall-through").

1. How the Switch Works

The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed.

A Switch block consists of:

2. Logical Flow

Think of a switch statement like a railway junction where the train (program flow) is directed to a specific track based on the signal (variable value).

3. Difference: Switch vs If-Else If

Choosing between a long ladder of if-else and a switch depends on readability and performance:

Readability

Switch is much cleaner when checking one variable against many constant values.

Speed

For a large number of cases, the compiler can optimize switch using a "Jump Table," making it faster than if-else.

Flexibility

if-else can check ranges (x > 10), while switch only checks for exact equality.

4. Rules of Switch

Keep these rules in mind to avoid compilation errors:

  1. Unique Cases: Duplicate case values are not allowed.
  2. Constant Values: The value for a case must be a constant or a literal (not a variable).
  3. Default Position: The default case is usually at the end, but it can technically be anywhere.
  4. Data Types: Works with primitives like int but not with float or double.

5. Comparison: break vs no-break

Feature Using break Omitting break (Fall-through)
Execution Exits the switch immediately. Executes all following cases.
Use Case Standard logic. When multiple cases share the same code.

6. Code Example

int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 4:
    System.out.println("Thursday"); // This will run
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}

Final Verdict

The Switch statement is a powerful tool for menu-driven programs and handling distinct states. It makes your code elegant and professional.

Next: Learn Java While Loop →