Introduction
The switch
statement in Java allows you to execute one out of multiple possible blocks of code based on the value of a given expression. It is often used to simplify complex if-else conditions.
Syntax of the Switch Statement
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if expression doesn't match any case
}
Key Points:
- The expression in a switch statement can be an integer, character, byte, or string (since Java 7).
- The
case
labels must be unique. - If no
break
statement is used, execution will "fall through" to the next case. - The
default
case is optional and executed if no matching case is found.
Examples of the Switch Statement
1. Basic Example
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println(dayName);
Output:
Wednesday
Unsolved Problems
- Write a program that uses a switch statement to determine the name of the day of the week based on an input number (1-7).
- Write a program that calculates the month of the year based on the user's input number (1-12).
- Write a program to determine if a given year is a leap year using a switch statement.
- Write a program to calculate the number of days in a month (taking into account leap years) using a switch statement.
- Write a program that uses a switch statement to print different messages based on the user's input age group (child, teenager, adult, senior).