The switch statement in Java is used to make decisions based on a specific value. It’s helpful when you have several options to choose from, so instead of using many if-else statements, you can use switch to make the code easier to read.
Here’s the basic structure of a switch statement:
switch (expression) {
case value1:
// Code to run if expression equals value1
break;
case value2:
// Code to run if expression equals value2
break;
// Add more cases as needed
default:
// Code to run if none of the cases match
}
Explanation:
expression: This is the variable you want to check.case value: Each case checks if theexpressionmatches a specific value. If it does, the code in that case runs.break: This ends the case so the program doesn’t run into the next one.default: This is optional; it runs if no cases match.
Example
Let's say you want to print the day of the week based on a number:
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;
default:
System.out.println("Invalid day");
}
day is 3, the output will be "Wednesday".
لأ
ReplyDelete