Java Reference
In-Depth Information
Listing 5-1. A simple if statement
if (a > 0) {
b = 1;
}
Let's examine a little more complex example. It's more realistic, but programs often make simple
comparisons, so both Listing 5-1 and Listing 5-2 are realistic. Here's part of a program that generates an
appropriate greeting based on the current time of day.
Listing 5-2. A more complex if statement example
GregorianCalendar gregorianCalendar = new GregorianCalendar();
int hour = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
String greeting = "Good ";
if (hour < 12) {
greeting += "morning";
}
The condition is simply whether the hour of the day is before 12 (that is, noon). If the hour of the day
is before noon, we add “morning” to our greeting. For conditions, the equality operators ( == and != ) and
the comparison operators ( > , < , <= , >= ) are often used. However, any condition that evaluates to true or
false works for a condition.
So what should our program do when it's not morning? For that case, we can use the else keyword
and have another block of code that gets run for afternoons. Listing 5-2 shows that code.
Listing 5-2. if-else statement example
GregorianCalendar gregorianCalendar = new GregorianCalendar();
int hour = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
String greeting = "Good ";
if (hour < 12) {
greeting += "morning";
} else {
greeting += "afternoon";
}
This structure represents a common arrangement in all software. Often, we need consider only two
alternatives. In this case, though, we have a problem. Late in the day, we say, “Good evening,” rather
than “Good afternoon.” So let's address that problem with some more code. In this case, we create a
structure called an else - if . It's possible, as we see later, to create long chains of branches with else-if
structures. Let's start with a fairly simple one, though, as shown in Listing 5-3.
Listing 5-3. else-if example
GregorianCalendar gregorianCalendar = new GregorianCalendar();
int hour = gregorianCalendar.get(Calendar.HOUR_OF_DAY);
String greeting = "Good ";
if (hour < 12) {
greeting += "morning";
} else if (hour < 18) {
greeting += "afterooon";
Search WWH ::




Custom Search