Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 185

Combining case Values

Оглавление

Notice something new in Figure 3.3? Starting with Java 14, case values can now be combined:

switch(animal) { case 1,2: System.out.print("Lion"); case 3: System.out.print("Tiger"); }

Prior to Java 14, the equivalent code would have been the following:

switch(animal) { case 1: case 2: System.out.print("Lion"); case 3: System.out.print("Tiger"); }

As you see shortly, switch expressions can reduce boilerplate code even more!

See if you can figure out why each of the following switch statements does not compile:

int month = 5; switch month { // DOES NOT COMPILE case 1: System.out.print("January"); } switch(month) // DOES NOT COMPILE case 1: System.out.print("January"); switch(month) { case 1: 2: System.out.print("January"); // DOES NOT COMPILE }

The first switch statement does not compile because it is missing parentheses around the switch variable. The second statement does not compile because it is missing braces around the switch body. The third statement does not compile because a comma (,) should be used to separate combined case statements, not a colon (:).

One last note you should be aware of for the exam: a switch statement is not required to contain any case statements. For example, this statement is perfectly valid:

switch(month) {}

Going back to our printDayOfWeek() method, we can rewrite it to use a switch statement instead of if/else statements:

public void printDayOfWeek(int day) { switch(day) { case 0: System.out.print("Sunday"); break; case 1: System.out.print("Monday"); break; case 2: System.out.print("Tuesday"); break; case 3: System.out.print("Wednesday"); break; case 4: System.out.print("Thursday"); break; case 5: System.out.print("Friday"); break; case 6: System.out.print("Saturday"); break; default: System.out.print("Invalid value"); break; } }

For simplicity, we just print a message if the value is invalid. If you know about exceptions or have already read Chapter 11, “Exceptions and Localization,” it might make more sense to throw an exception in the default branch if no match is found.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх