if-else vs switch
In Java, if-else and switch are both conditional control structures used to make decisions in a program. They help the program choose between different paths based on conditions.
- The if-else statement is flexible and supports complex logic, like range checks and multiple variables.
- The switch statement is cleaner and more efficient when you're checking one variable against multiple fixed values.
Even though both are used for decision-making, they have different use cases and limitations. Let’s compare them.
if-else vs switch in Java:
| Feature | if-else | switch |
|---|---|---|
| Use Case | Multiple complex conditions (any expression) | One variable compared with multiple constant values |
| Condition Type | Can use relational, logical, or any boolean logic | Only supports equality checks (==) |
| Data Types Supported | All types (int, float, boolean, etc.) | Only byte, short, int, char, enum, String |
| Fall-through Behavior | No fall-through – only one block runs | Yes, unless you use break |
| Readability | Can get messy with many conditions | Cleaner when checking one variable against many values |
| Execution Speed | Slightly slower when checking many conditions | Slightly faster with many cases (internally optimized) |
When to Use What?
- Use if-else when:
- You need complex conditions (like a > b && c < d)
- You're comparing different variables or ranges
- Use switch when:
- You're checking one variable against fixed values
- You want cleaner code for many exact matches
Example:
// Using if-else
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
}
// Using switch
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
}
Explanation:
if-else Block:
- We are checking the value of marks.
- If marks >= 90, it prints "Grade A".
- If not, but marks >= 80, it prints "Grade B".
- This is a range-based decision — perfect for if-else.
In this case, marks = 85, so it prints:
Grade B
switch Block:
- We are checking the value of a variable day.
- Based on the value (1 or 2), it prints the corresponding day name.
- This is a value-based selection — good use case for switch.
In this case, day = 2, so it matches case 2 and prints:
Tuesday
Summary:
- if-else is used for complex or range-based conditions.
- switch is used when checking one variable against fixed values.