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

Determining Acceptable Case Values

Оглавление

Not just any variable or value can be used in a case statement. First, the values in each case statement must be compile-time constant values of the same data type as the switch value. This means you can use only literals, enum constants, or final constant variables of the same data type. By final constant, we mean that the variable must be marked with the final modifier and initialized with a literal value in the same expression in which it is declared. For example, you can't have a case statement value that requires executing a method at runtime, even if that method always returns the same value. For these reasons, only the first and last case statements in the following example compile:

final int getCookies() { return 4; } void feedAnimals() { final int bananas = 1; int apples = 2; int numberOfAnimals = 3; final int cookies = getCookies(); switch(numberOfAnimals) { case bananas: case apples: // DOES NOT COMPILE case getCookies(): // DOES NOT COMPILE case cookies : // DOES NOT COMPILE case 3 * 5 : } }

The bananas variable is marked final, and its value is known at compile-time, so it is valid. The apples variable is not marked final, even though its value is known, so it is not permitted. The next two case statements, with values getCookies() and cookies, do not compile because methods are not evaluated until runtime, so they cannot be used as the value of a case statement, even if one of the values is stored in a final variable. The last case statement, with value 3 * 5, does compile, as expressions are allowed as case values, provided the value can be resolved at compile-time. They also must be able to fit in the switch data type without an explicit cast. We go into that in more detail shortly.

Next, the data type for case statements must match the data type of the switch variable. For example, you can't have a case statement of type String if the switch statement variable is of type int, since the types are incomparable.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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