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.
break keyword! Without it, Java will continue executing the next case regardless of the value (this is called "fall-through").
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:
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).
Choosing between a long ladder of if-else and a switch depends on readability and performance:
Switch is much cleaner when checking one variable against many constant values.
For a large number of cases, the compiler can optimize switch using a "Jump Table," making it faster than if-else.
if-else can check ranges (x > 10), while switch only checks for exact equality.
Keep these rules in mind to avoid compilation errors:
default case is usually at the end, but it can technically be anywhere.int but not with float or double.| 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. |
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 →