Switch statement and its use scenario
To review some of the features of switch statement in Java, which is part of the Java foundamental concept, I am writing this article. Also I will introduce it's enhanced statement after Java12.
The basics of a switch statement consist of the following:
- switch: the statement.
- case: how many cases to meet the requirement.
- execution: the behavior for each specific case.
- break: stop the loop; this includes the case and the default.
- default: when not meeting the above requirement, the execution of the behavior.
Traditional switch
Syntax
switch (val) {
case w:
execution;
break;
case x: case: y: case: z
execution;
break;
default:
execution;
break;
}
Example
int intTraditionalValue = 1;
switch (intTraditionalValue) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3: case 4: case 5:
System.out.println(intTraditionalValue);
break;
default:
System.out.println("none");
break;
}
// none
Used with method and return statement
Sometimes it goes with method and return statement, and executed in main method.
//main
String month = "April";
String quarter = getQuarter(month);
System.out.println("Quarter for " + month + ": " + quarter);
// Quarter for April: second Q
public static String getQuarter(String month) {
switch (month) {
case "January":
case "February":
case "March":
return "first Q";
case "April":
case "May":
case "June":
return "second Q";
case "July":
case "August":
case "September":
return "third Q";
case "October":
case "November":
case "December":
return "fourth Q";
default:
return "Invalid month";
}
Enhanced Swicth Statement
Omit break, simplify statement, this function appeared after Java 13.
Syntax
switch(val) {
case w →
case x, y, z →{}
default → n
}
Example
int intValue = 6;
switch(intValue) {
case 1 -> System.out.println("1");
case 2 -> System.out.println("2");
case 3, 4, 5 -> {
System.out.println(intValue);
}
default -> System.out.println("none");
}
I think that's it.