Table of Contents (Click any Topic to view first)
- Switch Statement Syntax:
- Example 1: Simple Switch Statement
- Example 2: Switch Statement with Fall-Through
- Example 3: Switch Statement with Enum
In Java programming, the switch statement provides an efficient way to execute different blocks of code based on the value of a variable or expression. It offers a cleaner alternative to multiple if-else-if statements when dealing with multiple possible values. Let's explore the switch statement in detail with examples.
switch (expression) {
case value1:
// Code block executed if expression equals value1
break;
case value2:
// Code block executed if expression equals value2
break;
// Additional cases...
default:
// Code block executed if expression doesn't match any case
}
public class SimpleSwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
// More cases...
default:
dayName = "Invalid day";
}
System.out.println("Day is: " + dayName);
}
}
In this example, based on the value of the day
variable, the program assigns a corresponding dayName
. If the value doesn't match any case, it sets dayName
to "Invalid day."
public class FallThroughSwitchExample {
public static void main(String[] args) {
int day = 2;
String dayType;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
dayType = "Weekday";
break;
case 6:
case 7:
dayType = "Weekend";
break;
default:
dayType = "Invalid day";
}
System.out.println("Day type is: " + dayType);
}
}
This example demonstrates fall-through in switch statements. If the day
is between 1 and 5 (inclusive), it sets dayType
to "Weekday." If it's 6 or 7, it sets dayType
to "Weekend."
public class EnumSwitchExample {
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
public static void main(String[] args) {
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("It's Monday!");
break;
// More cases...
default:
System.out.println("Invalid day");
}
}
}
In this example, the switch statement works with an enum type Day
. It prints a specific message based on the value of the day
variable.
public class StringSwitchExample {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("It's an apple!");
break;
// More cases...
default:
System.out.println("Unknown fruit");
}
}
}
This example showcases the usage of switch statements with string literals, which is supported in Java 7 and later versions.
Conclusion:
The switch statement in Java provides a concise and efficient way to handle multiple cases based on the value of an expression. Whether working with numerical values, enums, or strings, switch statements offer a clean and readable alternative to cascading if-else statements.