Hour 7. Using Conditional Tests To Make Decisions: Hear That Bouncing Noise? It's Your Checks
Hour 7. Using Conditional Tests To Make Decisions: Hear That Bouncing Noise? It's Your Checks
Writing a computer program has been compared to telling a household robot what to do. You provide the
computer a list of instructions, called statements, and these instructions are followed to the letter. You can
tell the computer to work out some unpleasant mathematical formulas, and it will work them out for you.
Tell it to display some information, and it will dutifully respond.
However, there are times when you need the computer to be more selective about what it does. For
example, if you have written a program to balance your checkbook, you might want the computer to display
a warning message if your account is overdrawn. The warning could be something along the lines of Hear
that bouncing noise? It's your checks. The computer should display this message only if
your account is overdrawn. If it isn't, the message would be both inaccurate and emotionally upsetting.
The way to accomplish this task in a Java program is to use a statement called a conditional. Conditionals
cause something to happen in a program only if a specific condition is met. During this hour, you'll learn
how to use three different types of conditional statements: if, else, and switch. The following topics will
be covered:
Testing a Condition
Whenever a Java program makes a decision, it does so by employing a conditional statement.
During this hour, you'll be checking the condition of several things in your Java programs using the
conditional statements if, else, switch, case, and break. You will also be using several
conditional operators: ==, !=, <, >, and ?, along with boolean variables.
if Statements
If you want to test a condition in a Java program, the most basic way is with an if statement. As you
learned previously, the boolean variable type is used to store only two possible values: true or false.
The if statement works along the same lines, testing to see whether a condition is true or false, and taking
Although this code is listed on two lines, it's one statement. The first part uses if to determine whether the
account variable is less than 0.01 (1 cent) by using the < operator. The second part displays the text
Hear that bouncing noise? It's your checks.
The second part of an if statement will be run only if the first part is true. In the preceding example, if the
account variable has a value of 0.01 or higher, the println statement will be ignored. Note that the
condition you test with an if statement must be surrounded by parentheses, as in (account < 0.01).
Note
If you're not sure why if (account < 0.01) is not a statement, note that there is no semicolon at the
end of the line. In Java programs, semicolons are used to show where one statement ends and the next
one begins. In the preceding example, the semicolon does not appear until after the println portion of
the statement. If you put a semicolon after the if portion, as in if (account < 0.01);, you'll cause a
logic error in your program that can be hard to spot. Take care regarding semicolons when you start using
the if statement.
The less-than operator, <, is one of several different operators you can use with conditional statements.
You'll become more familiar with the if statement as you use it with some of the other operators.
In the preceding section, the < operator is used the same way it was used in math class: as a less-than
sign. There is also a greater-than conditional operator: >. This operator is used in the following statements:
One thing to understand about if statements is that they often cause nothing to happen in your programs.
If the two preceding statements are used in a program where elephantWeight is equal to 600 and
elephantTotal is equal to 10, the rest of the if statements will be ignored.
There will be times when you want to determine whether something is less than or equal to something else.
You can do this with the <= operator, as you might expect; use the >= operator for greater-than-or-equal-to
if (account <= 0)
System.out.println("Hear that bouncing noise? It's your checks");
This revision of the checkbook example mentioned previously should be a bit easier to understand. It tests
whether account is less than or equal to the value 0, and taunts the user if it is.
Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable
equal to the value of another? These questions can be answered with the == operator, as in the following
statements:
if (answer == rightAnswer)
studentGrade = studentGrade + 10;
if (studentGrade == 100)
System.out.println("Such a show off!");
Note
The operator used to conduct equality tests has two equal signs: ==. It's very easy to confuse this operator
with the = operator, which is used to give a value to a variable. Always use two equal signs in a conditional
statement.
You can also test inequality—whether something is not equal to something else. This is accomplished with
the != operator, as shown in the following example:
if (answer != rightAnswer)
score = score - 5;
You can use the == and != operators reliably with every type of variable except one: strings. To see
whether one string has the value of another, use the equals() method described during Hour 6, "Using
Strings to Communicate."
Organizing a Program with Block Statements
Up to this point, all of the if statements have been followed with a single instruction, such as the
println() method. In many cases, you will want to perform more than one action in response to an if
statement. To do this, you'll use the { and } characters to create a block statement. I believe the technical
Block statements are statements that are organized into a group. Previously, you have seen how block
statements are used to mark the beginning and end of the main() block of a Java program. Each
statement within the main() block is handled when the program is run. Listing 7.1 is an example of a Java
program with a block statement used to denote the main() block. The block statement begins with the
opening bracket { on Line 2 and ends with the closing bracket } on Line 11. Load your word processor and
1: class Game {
2: public static void main(String[] arguments) {
3: int total = 0;
4: int score = 7;
5: if (score == 7)
6: System.out.println("You score a touchdown!");
7: if (score == 3)
8: System.out.println("You kick a field goal!");
9: total = total + score;
10: System.out.println("Total score: " + total);
11: }
12: }
Save this file as Game.java and compile it. If you're using the SDK, you can compile it by typing the
following command:
javac Game.java
When you run the program, the output should resemble Listing 7.2.
block statement:
The brackets are used to group all statements that are part of the if statement. If the variable
playerScore is greater than 9,999, three things will happen:
The value of the playerLives variable increases by one (because the increment operator ++ is
used).
If the variable playerScore is not greater than 9,999, nothing will happen. All three statements inside the
if statement block will be ignored.
if-else Statements
There are times when you want to do something if a condition is true and do something else if the condition
is false. You can do this by using the else statement in addition to the if statement, as in the following
example:
if (answer == correctAnswer) {
score += 10;
System.out.println("That's right. You get 10 points.");
}
else {
score -= 5;
System.out.println("Sorry, that's wrong. You lose 5 points.");
}
The else statement does not have a condition listed alongside it, unlike the if statement. Generally, the
else statement is matched with the if statement that immediately comes before it in a Java program.
You also can use else to chain several if statements together, as in the following example:
if (grade == 'A')
System.out.println("You got an A. Great job!");
else if (grade == 'B')
System.out.println("You got a B. Good work!");
else if (grade == 'C')
System.out.println("You got a C. You'll never get into a good "
+ "college!");
else
System.out.println("You got an F. You'll do well in Congress!");
By putting together several different if and else statements in this way, you can handle a variety of
conditions. In the preceding example, a specific message is sent to A students, B students, C students, and
future legislators
switch Statements
The if and else statements are good for situations with only two possible conditions, but there are times
when you have more than two options that need to be considered. With the preceding grade example, you
saw that if and else statements can be chained to handle several different conditions.
Another way to do this is to use the switch statement. You can use it in a Java program to test for a
variety of different conditions and respond accordingly. In the following example, the grade example has
been rewritten with the switch statement to handle a complicated range of choices:
switch (grade) {
case 'A':
System.out.println("You got an A. Great job!");
break;
case 'B':
System.out.println("You got a B. Good work!");
break;
case 'C':
System.out.println ("You got a C. You'll never get into a good "
+ "college!");
break;
default:
System.out.println("You got an F. You'll do well in Congress!");
}
The first line of the switch statement specifies the variable that will be tested—in this example, grade.
Then the switch statement uses the { and } brackets to form a block statement.
Each of the case statements checks the test variable in the switch statement against a specific value.
The value used in a case statement must be either a character or an integer. In this example, there are
case statements for the characters 'A', 'B', and 'C'. Each of these has one or two statements that
follow it. When one of these case statements matches the variable listed with switch, the computer
handles the statements after the case statement until it encounters a break statement.
For example, if the grade variable has the value of B, the text You got a B. Good work! will be
displayed. The next statement is break, so no other part of the switch statement will be considered. The
break statement tells the computer to break out of the switch statement.
The default statement is used as a catch-all if none of the preceding case statements is true. In this
example, it will occur if the grade variable does not equal 'A', 'B', or 'C'. You do not have to use a
default statement with every switch block statement you use in your programs. If it is omitted, nothing
will happen if none of the case statements has the correct value.
Note
One thing you might want to do with switch is to make each case statement represent a range of values.
As an example, in a grading program, you might want to use an integer called numberGrade and test for
case numberGrade > 89:. Unfortunately, this isn't possible in Java because each case statement
must refer to a single value. You'll have to use a series of if statements or if-else statements when you
The most complicated conditional statement is one that you might not find reasons to use in your programs:
the ternary operator. If you find it too confusing to implement in your own programs, take heart—you can
use other conditionals to accomplish the same thing.
You can use the ternary operator when you want to assign a value or display a value based on a
conditional test. For example, in a video game, you might need to set the numberOfEnemies variable
based on whether the skillLevel variable is greater than 5. One way to do this is with an if-else
statement:
if (skillLevel > 5)
numberOfEnemies = 10;
else
numberOfEnemies = 5;
A shorter way to do this is to use the ternary operator, which is ?. A ternary operator has five parts:
A colon (:)
To use the ternary operator to set the value of numberOfEnemies based on skillLevel, you could
You also can use the ternary operator to determine what information to display. Consider the example of a
program that displays the text Mr. or Ms. depending on the value of the gender variable. You could do
this action with another if-else statement:
if (gender.equals("male"))
System.out.print("Mr.");
else
System.out.print("Ms.");
A shorter method is to use the ternary operator to accomplish the same thing, as in the following:
The ternary operator can be useful, but it's also the hardest conditional in Java to understand. As you learn
Java, you won't encounter any situations where the ternary operator must be used instead of if and else
statements.
This hour's workshop gives you another look at each of the conditional tests you can use in your programs.
For this project, you will use Java's built-in timekeeping feature, which keeps track of the current date and
time, and present this information in sentence form.
Run the word processor you're using to create Java programs and give a new document the name
ClockTalk.java. This program is long, but most of it consists of long conditional statements. Type the
full text of Listing 7.3 into the word processor and save the file as ClockTalk.java when you're done.
1: import java.util.*;
2:
3: class ClockTalk {
4: public static void main(String[] arguments) {
5: // get current time and date
6: Calendar now = Calendar.getInstance();
7: int hour = now.get(Calendar.HOUR_OF_DAY);
8: int minute = now.get(Calendar.MINUTE);
9: int month = now.get(Calendar.MONTH) + 1;
10: int day = now.get(Calendar.DAY_OF_MONTH);
11: int year = now.get(Calendar.YEAR);
12:
13: // display greeting
14: if (hour < 12)
15: System.out.println("Good morning.\n");
16: else if (hour < 17)
17: System.out.println("Good afternoon.\n");
18: else
19: System.out.println("Good evening.\n");
20:
21: // begin time message by showing the minutes
22: System.out.print("It's");
23: if (minute != 0) {
24: System.out.print(" " + minute + " ");
25: System.out.print( (minute != 1) ? "minutes" :
26: "minute");
27: System.out.print(" past");
28: }
29:
30: // display the hour
31: System.out.print(" ");
32: System.out.print( (hour > 12) ? (hour - 12) : hour );
33: System.out.print(" o'clock on ");
34:
35: // display the name of the month
36: switch (month) {
37: case 1:
38: System.out.print("January");
39: break;
40: case 2:
41: System.out.print("February");
42: break;
43: case 3:
44: System.out.print("March");
45: break;
46: case 4:
47: System.out.print("April");
48: break;
49: case 5:
50: System.out.print("May");
51: break;
52: case 6:
53: System.out.print("June");
54: break;
55: case 7:
56: System.out.print("July");
57: break;
58: case 8:
59: System.out.print("August");
60: break;
61: case 9:
62: System.out.print("September");
63: break;
64: case 10:
65: System.out.print("October");
66: break;
67: case 11:
68: System.out.print("November");
69: break;
70: case 12:
71: System.out.print("December");
72: }
73:
74: // display the date and year
75: System.out.println(" " + day + ", " + year + ".");
76: }
77: }
Save the file when you're done, and attempt to compile it (SDK users can enter javac ClockTalk.java
at the command line). Correct any typos that cause error messages to occur during the attempted
compilation. After the program compiles correctly, look over Lines 13–75 before going over the description
of the program. See whether you can get a good idea about what is taking place in each of these sections
and how the conditional tests are being used.
With the exception of Lines 6–11, the ClockTalk program contains material that has been covered up to
this point. After a series of variables are set up to hold the current date and time, a series of if or switch
display strings.
Lines 6–11 refer to a Calendar variable called now. The Calendar variable type is capitalized, just as
String is capitalized in a program that uses strings. The reason for the capitalization is that Calendar is
an object.
You'll learn how to create and work with objects during Hour 10, "Creating Your First Object." For this hour,
focus on what's taking place in Lines 6–11 rather than how it's happening.
Line 1 enables your program to use a class that is needed to track the current date and time:
java.util.Calendar.
Lines 3–4 begin the ClockTalk program and its main() statement block.
Line 6 creates a Calendar object called now that contains the current date and time of your
system. The now object will change each time you run this program (unless, of course, the physical
Lines 7–11 create variables to hold the hour, minute, month, day, and year. The values for
these variables are pulled from the Calendar object, which is the storehouse for all of this
information. These variables are used in the subsequent sections as the program displays information.
Lines 14–19 display one of three possible greetings: Good morning., Good afternoon., or
Good evening. The greeting to display is selected based on the value of the hour variable.
Lines 22–28 display the current minute along with some accompanying text. First, the text It's is
displayed in Line 22. If the value of minute is equal to 0, Lines 24–27 are ignored because of the if
statement in Line 23. This statement is necessary because it would not make sense for the program to
tell someone that it's 0 minutes past an hour. Line 24 displays the current value of the minute
variable. A ternary operator is used in Lines 25–26 to display either the text minutes or minute,
depending on whether minute is equal to 1. Finally, in Line 27 the text past is displayed.
Lines 30–33 display the current hour by using another ternary operator. This ternary conditional
statement in Line 32 causes the hour to be displayed differently if it is larger than 12, which prevents
the computer from stating things like 15 o'clock.
Lines 35–72 , almost half of the program, are a long switch statement that displays a different
name of the month based on the integer value stored in the month variable.
Lines 74–75 finish off the display by showing the current date and the year.
Lines 76–77 close out the main() statement block and then the entire ClockTalk program.
When you run this program, the output should resemble the following code, with changes based on the
current date and time. For example, if the program was run on 7/5/2002 at 11:36 p.m., it would display the
following text:
Good evening.
Run the program several times to see how it keeps up with the clock. If the time doesn't match the time on
your computer, the Java interpreter might be using the wrong time zone to determine the current time.
When the interpreter does not know the default time zone to use, it uses Greenwich Time instead.
TimeZone tz = TimeZone.getTimeZone("EST");
TimeZone.setDefault(tz);
The setDefault() method should be used before calendar or any other date-related items are
created.
The first statement creates a TimeZone object called tz. The text EST is sent as an argument to the
getTimeZone () method, and this causes TimeZone to be set up for Eastern Standard Time.
The second statement sets the time zone by calling the setDefault () method of the TimeZone class.
If you're having trouble finding the right time zone arguments, the following statements display all valid
zones recognized by Java on your system:
Western world for many years to determine the date and time.
Summary
Now that you can use conditional statements, the overall intelligence of your Java programs has improved
greatly. Your programs can now evaluate information and use it to react differently in different situations,
even if information changes as the program is running. They can decide between two or more alternatives
based on specific conditions.
Programming a computer forces you to break a task down into a logical set of steps to undertake any
decisions that must be made. Using the if statement and other conditionals in programming also
promotes a type of logical thinking that can reap benefits in other aspects of your life:
"If he is elected president in November, I will seek a Cabinet position, else I will move to Canada."
"If my blind date is attractive, I'll pay for dinner at an expensive restaurant, else we will go to
Edgar's Taco Barn."
"If I violate my probation, the only team that will draft me is the Dallas Cowboys."