switch case Statements
The switch statement in Java is used for multi-way branching, allowing you to execute different code blocks based on the value of an expression. It provides a concise way to write code for multiple possible cases. Each case represents a different value, and the code inside the corresponding case block is executed when the value matches the expression.
Example:
public class SwitchStatementExample {
public static void main(String[] args) {
int dayOfWeek = 3;
switch (dayOfWeek) {
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 of the week");
}
}
}
In this example:
- The
switchstatement is based on the value ofdayOfWeek. - Each
caserepresents a different day of the week. - The code inside the corresponding
caseblock is executed when the value matches. - The
breakstatement is used to exit theswitchblock after a case is matched. - If none of the cases match, the code inside the
defaultblock is executed.
It's important to note that switch expressions can be of integral types (byte, short, int, char) or an enumeration type. Starting from Java 12, switch expressions can also be used with String expressions.
public class SwitchStringExample {
public static void main(String[] args) {
String dayOfWeek = "Wednesday";
switch (dayOfWeek) {
case "Monday":
System.out.println("Start of the week");
break;
case "Wednesday":
System.out.println("Midweek");
break;
case "Friday":
System.out.println("End of the week");
break;
default:
System.out.println("Invalid day");
}
}
}
Using switch can make the code more readable and concise when dealing with multiple cases compared to a series of nested if...else statements.