A switch statement executes statements based on the value of a variable or an expression.
Switch statements simply working with several conditions.
Normally an if statement
makes selctions based on a single true
or false
condition.
Switch statements have the following syntax:
switch (key) {
case value1:
break;
case value2:
break;
case value3:
break;
default:
break;
}
Here's how switch statements work and the rules to take into account:
The switch expression must yield a value of
The values in the case
statement must be of the same data type. And they need to be constant expressions, meaning they must not contain variables like value1+value2
.
When a match is made in a case statement, the statements defined in the body of that case statement are executed until a break statement is encountered. This is referred to a s a fall through behavior.
The default case is optional. It can be used to perform actions when none of the specified cases match the switch expression.
Example
import java.util.Scanner;
public class MrSwitch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Your Day Code: ");
int day = input.nextInt();
switch (day) {
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("Date out of Range");
break;
}
}
}
Result
Enter Your Day Code: 4
Thursday