The switch-case construct in Java is a flow control structure designed to evaluate the value of a variable against a list of predefined values. The syntax for this structure is as follows:
switch (expression) {
case constant_1:
// statement 1
break;
case constant_2:
// statement 2
break;
case constant_3:
// statement 3
break;
//...
case constant_n:
// statement n
break;
default:
// if none of the cases match
}
Here are some rules regarding the switch-case construct:
constant_1
, constant_2
, ..., constant_n
) must be literals or constants of the allowed types.default
case will be executed if no matching case is found.Let's explore some examples of switch-case in Java:
Example 1:
int number = 3;
String text = "";
switch (number) {
case 1:
text = "One";
break;
case 2:
text = "Two";
break;
case 3:
text = "Three";
break;
default:
text = "Other number";
}
System.out.println("The number is: " + text);
Example 2:
String planet = "Jupiter";
long distanceFromEarth = 0;
switch (planet) {
case "Mars":
distanceFromEarth = 3;
break;
case "Saturn":
distanceFromEarth = 5;
break;
case "Jupiter":
distanceFromEarth = 4;
break;
case "Venus":
distanceFromEarth = 1;
break;
}
System.out.println("The distance from earth to " + planet + " is: " + distanceFromEarth);
Example 3:
Priority priority = Priority.HIGH;
int taskPriority = 0;
switch (priority) {
case LOW:
taskPriority = 1;
break;
case NORMAL:
taskPriority = 2;
break;
case HIGH:
taskPriority = 3;
break;
case SEVERE:
taskPriority = 4;
break;
}
System.out.println("Task priority: " + taskPriority);
The enum Priority
is declared as follows:
public enum Priority { LOW, NORMAL, HIGH, SEVERE }
Starting from Java 14, you can use the switch block as an expression:
int taskPriority = switch (priority) {
case LOW -> 1;
case NORMAL -> 2;
case HIGH -> 3;
case SEVERE -> 4;
};
System.out.println("Task priority: " + taskPriority);