Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 183
Applying switch Statements
ОглавлениеWhat if we have a lot of possible branches or paths for a single value? For example, we might want to print a different message based on the day of the week. We could certainly accomplish this with a combination of seven if
or else
statements, but that tends to create code that is long, difficult to read, and often not fun to maintain:
public void printDayOfWeek(int day) { if(day == 0) System.out.print("Sunday"); else if(day == 1) System.out.print("Monday"); else if(day == 2) System.out.print("Tuesday"); else if(day == 3) System.out.print("Wednesday"); … }
Luckily, Java, along with many other languages, provides a cleaner approach. In this section we present the switch
statement, along with the newer switch
expression for controlling program flow.