How to write Java switch
Statement
The switch
statement in Java allows you to execute one block of code among many alternatives. It’s a cleaner and more readable alternative to using multiple if-else
conditions when testing the same variable against several values.
1. Syntax of switch
switch (expression) {
case value1:
// Code to execute if expression equals value1
break; // Optional, but necessary to prevent fall-through
case value2:
// Code to execute if expression equals value2
break;
// Add more cases as needed
default:
// Code to execute if expression doesn't match any case
}
- The expression inside the
switch
statement is evaluated once, and the value of the expression is compared with eachcase
value. - If a match is found, the corresponding block of code is executed.
- The
break
keyword is used to exit the switch statement, preventing the execution from falling through to subsequent cases. - The
default
block is optional and runs if nocase
matches.
2. Example of a switch
Statement
public class Main {
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"); // Outputs: Wednesday
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
}
}
}
In this example, since day
is 3
, the code inside the case 3:
block is executed, printing "Wednesday"
to the console.
3. break
Statement
In a switch
statement, the break
statement is crucial. Without it, the code will continue to execute the subsequent cases, even if a match has already been found. This is known as fall-through behavior.
Example Without break
:
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday"); // Outputs: Wednesday
case 4:
System.out.println("Thursday"); // Also prints this
case 5:
System.out.println("Friday"); // And this
default:
System.out.println("Weekend"); // And this
}
}
}
In this case, without the break
statements, Java will execute all the cases starting from the matched case (case 3
) until the end of the switch block, leading to unexpected output.
4. default
Case
The default
case in a switch
statement is optional and will be executed if none of the case
values match the expression. It acts as a fallback for unmatched cases.
Example:
public class Main {
public static void main(String[] args) {
int day = 7;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day"); // Outputs: Invalid day
}
}
}
Here, since day
is 7 and there is no case for 7, the default
block is executed, printing "Invalid day"
.
5. Multiple Case Labels
You can group multiple case labels together if they should execute the same block of code. This is useful for conditions where multiple values have the same outcome.
Example:
public class Main {
public static void main(String[] args) {
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend"); // Outputs: Weekend
break;
}
}
}
In this example, both case 6
and case 7
will print "Weekend"
to the console.
6. Data Types Supported by switch
The switch
statement in Java supports the following data types:
- byte, short, int, char: The most common types used in
switch
statements. - String: Since Java SE 7, you can use
String
inswitch
expressions. - enum: You can also use enum constants in a
switch
statement.
7. Using switch
with Strings
Since Java SE 7, you can use a String
expression in a switch
statement, making it easier to work with text-based conditions.
Example:
public class Main {
public static void main(String[] args) {
String day = "Tuesday";
switch (day) {
case "Monday":
System.out.println("Start of the week");
break;
case "Tuesday":
System.out.println("Second day of the week"); // Outputs: Second day of the week
break;
case "Wednesday":
System.out.println("Midweek");
break;
default:
System.out.println("Unknown day");
}
}
}
Here, the expression is a String
, and the switch
statement compares the value of day
to each case
string.
8. Example with enum
Type
You can also use enum
types in a switch
statement. An enum
is a special data type that represents a group of constants.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
public static void main(String[] args) {
Day day = Day.WEDNESDAY;
switch (day) {
case MONDAY:
System.out.println("Start of the week");
break;
case WEDNESDAY:
System.out.println("Midweek"); // Outputs: Midweek
break;
case FRIDAY:
System.out.println("End of the workweek");
break;
default:
System.out.println("Weekend");
}
}
}
In this example, the enum
type Day
is used in the switch
statement, making it easy to handle specific days of the week.
9. Summary
- The
switch
statement is a cleaner alternative to using multipleif-else
conditions when testing the same variable. - Always use
break
to prevent fall-through behavior. - The
default
case handles unmatched conditions. - You can use
int
,char
,String
,enum
, and other primitive data types inswitch
statements. - Grouping
case
labels allows for multiple conditions to execute the same block of code.
By using switch
, you can make your code more organized and easier to read, especially when working with multiple conditions based on a single expression.