If you are a developer, there is a high chance that you have already know a feature called Switch in which has appeared in majority of programming languages. Using switch is often very lengthy and that is why sometime if-else statement is used. However, enhanced switch come into action to address this problem in the modern latest Java version.
To give you more understanding, I will give you an example of classic Java switch and also the enchanced one.
Classic Switch
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;
}
Enhanced Switch
public String toDayStringUsingSwitch(int dayIndex) {
return switch (dayIndex) {
case 1 -> "Sunday";
case 2 -> "Monday";
case 3 -> "Tuesday";
case 4 -> "Wednesday";
case 5 -> "Thursday";
case 6 -> "Friday";
case 7 -> "Saturday";
default -> throw new IllegalArgumentException("Invalid day index");
};
}
From the above example, you can see that the lines of code is reduced significantly by using the enhanced Java switch, and I personally think that the enchanced version of switch is more readable if compare to the classic version.
If you not yet familiar to Switch Statement, you might want to check the following article: What Is Switch Statement
Image cover:
https://i.picsum.photos/id/650/1920/720.jpg?hmac=tz4eU3jOg0EzPCvHIjfNrmhsBBod2_2OpGBBmARc6B0
Top comments (1)
Same approach as Kotlin, very useful