OCP Oracle Certified Professional Java SE 17 Developer Study Guide. Jeanne Boyarsky
Чтение книги онлайн.

Читать онлайн книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky страница 66

Название: OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Автор: Jeanne Boyarsky

Издательство: John Wiley & Sons Limited

Жанр: Программы

Серия:

isbn: 9781119864592

isbn:

СКАЧАТЬ NOT COMPILE case 1 -> "dog"; case 2 -> "wolf"; case 3 -> "coyote"; };

      There's no case branch to cover 5 (or 4, -1, 0, etc.), so should the switch expression return null, the empty string, undefined, or some other value? When adding switch expressions to the Java language, the authors decided this behavior would be unsupported. Every switch expression must handle all possible values of the switch variable. As a developer, there are two ways to address this:

       Add a default branch.

       If the switch expression takes an enum value, add a case branch for every possible enum value.

      In practice, the first solution is the one most often used. The second solution applies only to switch expressions that take an enum. You can try writing case statements for all possible int values, but we promise it doesn't work! Even smaller types like byte are not permitted by the compiler, despite there being only 256 possible values.

      For enums, the second solution works well when the number of enum values is relatively small. For example, consider the following enum definition and method:

      enum Season {WINTER, SPRING, SUMMER, FALL} String getWeather(Season value) { return switch(value) { case WINTER -> "Cold"; case SPRING -> "Rainy"; case SUMMER -> "Hot"; case FALL -> "Warm"; }; }

      Tip Icon What happens if you use an enum with three values and later someone adds a fourth value? Any switch expressions that use the enum without a default branch will suddenly fail to compile. If this was done frequently, you might have a lot of code to fix! For this reason, consider including a default branch in every switch expression, even those that involve enum values.

      A common practice when writing software is doing the same task some number of times. You could use the decision structures we have presented so far to accomplish this, but that's going to be a pretty long chain of if or else statements, especially if you have to execute the same thing 100 times or more.

      Enter loops! A loop is a repetitive control structure that can execute a statement of code multiple times in succession. By using variables that can be assigned new values, each repetition of the statement may be different. The following loop executes exactly 10 times:

      int counter = 0; while (counter < 10) { double price = counter * 10; System.out.println(price); counter++; }

      If you don't follow this code, don't panic—we cover it shortly. In this section, we're going to discuss the while loop and its two forms. In the next section, we move on to for loops, which have their roots in while loops.

      The while Statement

      As shown in Figure 3.5, a while loop is similar to an if statement in that it is composed of a boolean expression and a statement, or a block of statements. During execution, the boolean expression is evaluated before each iteration of the loop and exits if the evaluation returns false.

      Let's see how a loop can be used to model a mouse eating a meal:

      int roomInBelly = 5; public void eatCheese(int bitesOfCheese) { while (bitesOfCheese> 0 && roomInBelly> 0) { bitesOfCheese--; roomInBelly--; } System.out.println(bitesOfCheese+" pieces of cheese left"); }

      This method takes an amount of food—in this case, cheese—and continues until the mouse has no room in its belly or there is no food left to eat. With each iteration of the loop, the mouse “eats” one bite of food and loses one spot in its belly. By using a compound boolean statement, you ensure that the while loop can end for either of the conditions.

      One thing to remember is that a while loop may terminate after its first evaluation of the boolean expression. For example, how many times is Not full! printed in the following example?

      int full = 5; while(full < 5) { System.out.println("Not full!"); full++; }

      The answer? Zero! On the first iteration of the loop, the condition is reached, and the loop exits. This is why while loops are often used in places where you expect zero or more executions of the loop. Simply put, the body of the loop may not execute at all or may execute many times.

      The do/while Statement

Schematic illustration of the structure of a do/while statement

      Unlike a while loop, though, a do/while loop guarantees that the statement or block will be executed at least once. For example, what is the output of the following statements?

      int lizard = 0; do { lizard++; } while(false); System.out.println(lizard); // 1

      Java will execute the statement block first and then check the loop condition. Even though the loop exits right away, the statement block is still executed once, and the program prints 1.

      Infinite Loops

      The single most important thing you should be aware of when you are using any repetition control structures is to make sure they always terminate! Failure to terminate a loop can lead to numerous problems in practice, including overflow exceptions, memory leaks, slow performance, and even bad data. Let's take a look at an example:

      int СКАЧАТЬ