What Is Switch Statement
luthfisauqi17
Posted on September 3, 2022
Switch Statement is a feature in many programming languages that allow the programmer to eliminate numerous nested if-else constructs thus improving code clarity.
Take a look on the following example:
public String toDayStringUsingIf(int dayIndex) {
String result;
if (dayIndex == 0) {
result = "Sunday";
} else if (dayIndex == 1) {
result = "Monday";
} else if (dayIndex == 2) {
result = "Tuesday";
} else if (dayIndex == 3) {
result = "Wednesday";
} else if (dayIndex == 4) {
result = "Thursday";
} else if (dayIndex == 5) {
result = "Friday";
} else if (dayIndex == 6) {
result = "Saturday";
} else {
throw new IllegalArgumentException("Invalid day index");
}
return result;
}
In the switch statement form:
public String toDayStringUsingSwitch(int dayIndex) {
String result;
switch (dayIndex) {
case 1:
result = "Sunday";
break;
case 2:
result = "Monday";
break;
case 3:
result = "Tuesday";
break;
case 4:
result = "Wednesday";
break;
case 5:
result = "Thursday";
break;
case 6:
result = "Friday";
break;
case 7:
result = "Saturday";
break;
default:
throw new IllegalArgumentException("Invalid day index");
}
return result;
}
You can see individual cases more clearly in the switch statement, it makes other developer understand the code easily. It may still looks longer than the if-else statement, but there are some improvement in the enhanced version of switch statement that makes the code more leaner.. Even that Switch statement is more clearer than the if-else statement, there are several conditions that Switch statement cannot replace the if-else statement.
To learn more about the enhanced version of switch in Java, you could check this article: Enhanced Switch Statement in Java
To understand this concept even more, it is highly suggested to surf throughout the reference list down below.
References:
- https://docs.oracle.com/en/java/javase/13/language/switch-expressions.html
- https://www.w3schools.com/java/java_switch.asp
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
- https://www.baeldung.com/java-switch
Image cover
https://i.picsum.photos/id/42/1920/720.jpg?hmac=Cx0R9ISRIt0e1aHq11irofoe6qabiOl5Bpf668nqsiQ
Posted on September 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.