On Day 6, we continue learning conditional statements. While if-else
is useful, it can become long and repetitive when checking many conditions. The switch statement is a cleaner alternative, especially when comparing the same variable against multiple values.
1. Syntax of switch
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
How it works: Java evaluates the expression and jumps to the matching case. The break
statement prevents execution from falling through to the next case. The default
block runs if no case matches.
2. Example: 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;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output: Since day
is 3, the program prints Wednesday
.
3. When to Use switch vs if-else
- Use if-else for ranges (e.g., marks ≥ 90).
- Use switch when comparing a single variable against fixed values (like days of the week).
Summary
The switch
statement is a clean and efficient way to handle multiple choices in Java. It reduces repetition and makes code easier to read compared to long chains of else if
.