Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 174
The else Statement
ОглавлениеLet's expand our example a little. What if we want to display a different message if it is 11 a.m. or later? Can we do it using only the tools we have? Of course we can!
if(hourOfDay < 11) { System.out.println("Good Morning"); } if(hourOfDay >= 11) { System.out.println("Good Afternoon"); }
This seems a bit redundant, though, since we're performing an evaluation on hourOfDay
twice. Luckily, Java offers us a more useful approach in the form of an else
statement, as shown in Figure 3.2.
FIGURE 3.2 The structure of an else
statement
Let's return to this example:
if(hourOfDay < 11) { System.out.println("Good Morning"); } else System.out.println("Good Afternoon");
Now our code is truly branching between one of the two possible options, with the boolean
evaluation happening only once. The else
operator takes a statement or block of statements, in the same manner as the if
statement. Similarly, we can append additional if
statements to an else
block to arrive at a more refined example:
if(hourOfDay < 11) { System.out.println("Good Morning"); } else if(hourOfDay < 15) { System.out.println("Good Afternoon"); } else { System.out.println("Good Evening"); }
In this example, the Java process will continue execution until it encounters an if
statement that evaluates to true
. If neither of the first two expressions is true
, it will execute the final code of the else
block.