Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 172
The if Statement
ОглавлениеOften, we want to execute a block only under certain circumstances. The if
statement, as shown in Figure 3.1, accomplishes this by allowing our application to execute a particular block of code if and only if a boolean
expression evaluates to true
at runtime.
FIGURE 3.1 The structure of an if
statement
For example, imagine we had a function that used the hour of day, an integer value from 0
to 23
, to display a message to the user:
if(hourOfDay < 11) System.out.println("Good Morning");
If the hour of the day is less than 11, then the message will be displayed. Now let's say we also wanted to increment some value, morningGreetingCount
, every time the greeting is printed. We could write the if
statement twice, but luckily Java offers us a more natural approach using a block:
if(hourOfDay < 11) { System.out.println("Good Morning"); morningGreetingCount++; }