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 checkguide,
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'syour 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. Country star Kenny Rogers sang with the hippie-rock group The First
Edition in the late '60s, and one of the group's singles hit the top 5 in 1968: "Just
Dropped In (To See What Condition My Condition Was In)". During this hour, you'll
be dropping in to check the condition of several things in your Java programs using
the conditional statements if, else, switch, case,
and break. You also will be using several conditional operators: ==,
!=, <, >, and ?. The following topics will
be covered:
Testing to see whether conditions are met
Using the if statement for basic conditional tests
Using other statements in conjunction with if
Testing whether one value is greater than or less than another
Testing whether two values are equal or unequal
Using else statements as the opposite of if statements
Chaining several conditional tests together
Using the switch statement for complicated conditional tests
Creating complicated tests with the ternary operator
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 action only if the condition is true.
You use if along with a condition to test, as in the following statement:
if (account < 0.01)
System.out.println("Hear that bouncing noise? It's your checks");
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 by using the < operator. The second part displays the text Hear
that bouncing noise? It's your checks. The second part of the if statement
will be run only if the first part is true. If the account variable has
a value of 0.01 (1 cent) or higher, the println statement will be ignored.
Note that the condition that you test with an if statement must be surrounded
by parentheses, as in (account < 0.01).
If you're not sure why if (account < 0.01) is not a statement on its
own, 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 an 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 that
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.
Less Than and Greater
Than Comparisons
In the preceding section, the < operator is used the same way it was
used in math class, as a less-than sign. There also is a greater-than conditional
operator, >. This operator is used in the following statements:
if (elephantWeight > 780)
System.out.println("This elephant is too fat for your tightrope act.");
if (elephantTotal > 12)
cleaningExpense = cleaningExpense + 150;
The first if statement tests whether the value of the elephantWeight
variable is greater than 780. The second if statement tests whether the
elephantTotal variable is greater than 12.
One thing to learn about if statements is that they often cause nothing
to happen in your programs. If the preceding two statements are used in a program
where elephantWeight is equal to 600 and elephantTotal is equal
to 10, the rest of the statements will be ignored. It's as though you are giving
an order to a younger sibling who is subject to your whims: "Jerry, go to the
store. If they have Everlasting Gobstopper candy, buy some for me. If not, do nothing
and await further orders."
There will be times when you will 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
tests. Here's an example:
if (account <= 0)
System.out.println("Hear that bouncing noise? It's your checks");
This revision of the checkguide 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.
Equal and Not Equal
Comparisons
Another condition to check on 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 == value, as in the following statements:
if (answer == rightAnswer)
studentGrade = studentGrade + 10;
if (studentGrade == 100)
System.out.println("Congratulations -- a perfect score!");
Caution: 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 also can test inequality--whether something is not equal to something else.
You do this with the != operator, as shown in the following example:
if (team != "New York Jets")
chanceToWin = 50;
if (answer != rightAnswer)
score = score - 5;
You can use the == and != operators with every type of variable
except for one, strings. To see whether one string has the value of another, use
the equals() method described during Chapter 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 do more than one action in response to an if statement. To do this,
you'll use the squiggly bracket marks { and } to create a block statement.
Block statements are statements that are organized as 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 enter the text of Listing 7.1 as a new file.
Listing 7.1. A Java
program using a main() block statement.
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 with the javac compiler
tool. The output should resemble Listing 7.2.
Listing 7.2. The
output of the Game program.
You score a touchdown!
Total score: 7 You can also use block statements in conjunction with
if statements to make the computer do more than one thing if a conditional
statement is true. The following is an example of an if statement that includes
a 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).
The text Extra life! is displayed.
The value of the difficultyLevel variable is increased by 5.
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 from switch
against a specific value. In this example, there are case statements for
values of 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 that
you use in your programs. If it is omitted, nothing will happen if none of the case
statements has the correct value.
The Conditional
Operator
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:
A shorter way to do this is to use the ternary operator, which is ?.
A ternary operator has the following parts:
The condition to test, surrounded by parentheses, as in (skillLevel >
5)
A question mark (?)
The value to use if the condition is true
A colon (:)
The value to use if the condition is false
To use the ternary operator to set the value of numberOfEnemies based
on skillLevel, you could use the following statement:
numberOfEnemies = ( skillLevel > 5) ? 10 : 5;
You can also 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 == "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 element of conditional
tests in Java to understand. Feel free to use the longer if and else
statements if you want.
Workshop: Watching
the Clock
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 will present this information
in sentence form.
Run the word processor that 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 when you're done.
Listing 7.3. The
full text of ClockTalk.java.
1: import java.util.*;
2:
3: class ClockTalk {
4: public static void main(String[] arguments) {
5: // get current time and date
6: GregorianCalendar now = new GregorianCalendar();
7: int hour = now.get(Calendar.HOUROFDAY);
8: int minute = now.get(Calendar.MINUTE);
9: int month = now.get(Calendar.MONTH) + 1;
10: int day = now.get(Calendar.DAYOFMONTH);
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: }
Once you have saved the file, try to compile it by entering 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
14-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.
The ClockTalk program is made up of the following sections:
Line 1 enables your program to use two classes that are needed to track the current
date and time: java.util.Calendar and java.util.GregorianCalendar.
Lines 3-4 begin the ClockTalk program and its main() statement
block.
Line 6 creates a variable called now with a special type of variable
called a GregorianCalendar. The now variable stores the current
date and current time and will change each time you run this program (unless, of
course, the physical laws of the universe are altered and time stands still).
Lines 7-11 create variables to hold the hour, minute, month,
day, and year. These variables are used in the subsequent sections
as the program displays information.
Lines 14-19 display one of three possible greetings: Goodmorning.,
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 Line 25 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 36-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 today's date is 4-13-1997
and the time is 8:30 a.m., your program would display the following text:
Good morning.
It's 30 minutes past 8 o'clock on April 13, 1997.
Run the program several times to see how it keeps up with the clock.
The ClockTalk program uses the Gregorian calendar system that has been
used throughout the Western world for many years to determine the date and time.
It was introduced in 1582 when Pope Gregory XIII moved the Julian calendar system
forward 10 days--turning Oct. 5, 1582, into Oct. 15, 1582. This was needed because
the calendar was moving out of alignment with the seasons due to discrepancies in
the Julian system. Changes introduced with version 1.1 of the Java language make
it possible to create other calendar systems for use with Java programs. Check Gamelan
at http://www.gamelan.com or other
Java programming resources for these calendar systems as they become available.
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.
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 she's attractive, I'll take her to an expensive restaurant, else we're
using my two-for-one Taco Barn burrito coupon.") Programming a computer forces
you to break down a task into a logical set of steps to undertake and decisions that
must be made, and it provides interesting insight.
One thing that conditional statements do not offer insight about is the thinking
of the lyricist who penned "Just Dropped In (To See What Condition My Condition
Was In)". There may be no rational explanation for lyrics such as, "I tred
on a cloud, I fell eight miles high. Told my mind I'm gonna sky. I just dropped in
to see what condition my condition was in."
Q&A
Q The if statement seems like the one that's most useful. Is it possible to
use only if statements in programs and never use the others?
A It's possible to do without else or switch, and many programmers
never use the ternary operator ?. However, else and switch
often are beneficial to use in your programs because they make them easier to understand.
A set of if statements chained together can become unwieldy.
Q An if statement is described as a single statement or as a conditional statement
followed by another statement to handle if the condition is true. Which is it?
A The point that might be confusing is that if statements and other
conditionals are used in conjunction with other statements. The if statement
makes a decision, and the other statements do work based on the decision that is
made. The if statement combines a conditional statement with one or more
other types of Java statements, such as statements that use the println()
method or create a variable.
Q During this hour, opening and closing brackets { and } are not used with an
if statement if it is used in conjunction with only one statement. Is this mandatory?
A No. Brackets can be used as part of any if statement to surround the
part of the program that's dependent on the conditional test. Using brackets is a
good practice to get into because it prevents a common error that might take place
when you revise the program. If you add a second statement after an if conditional
and don't add brackets, unexpected errors will occur when the program is run.
Q Will the Java compiler javac catch the error when an = operator is used with
a conditional instead of an ==?
A Often no, and it results in a real doozy of a logic error. These errors only
show up when a program is being run and can be discovered only through observation
and testing. Because the = operator is used to assign a value to a variable,
if you use name = "Fernando" in a spot in a program where you
mean to use name == "Fernando", you could wipe out the value of
the name variable and replace it with Fernando. When the value
stored in variables changes unexpectedly, the result is subtle and unexpected errors
that you must debug.
Q Does break have to be used in each section of statements that follow a case?
A You don't have to use break. If you do not use it at the end of a
group of statements, all of the remaining statements inside the switch block
statement will be handled, regardless of the case value they are being tested
with.
Q What's the difference between System.out.println() and System.out.print()?
A The println() statement displays a line of text and ends the line
with a newline character. The newline character has the same behavior as the carriage
return key on a manual typewriter. It causes the next text to begin displaying at
the leftmost edge of the next line. The print() statement does not use a
newline character, making it possible to use several print() statements
to display information on the same line.
Quiz
The following questions will see what condition your knowledge of conditions is
in.
Questions
1. Conditional tests result in either a true or false value. Which variable
type does this remind you of?
(a) None. They're unique. (b) The long variable type. (c) The boolean type.
2. Which statement is used as a catch-all category in a switch block
statement?
(a)default (b)otherwise (c)onTheOtherHand
3. What's a conditional?
(a) The thing that repairs messy split ends and tangles after you shampoo. (b) Something in a program that tests whether a condition is true or false. (c) The place where you confess your sins to a neighborhood religious figure.
Answers
1. c. The boolean variable type can only equal true
or false, making it similar to conditional tests.
2. a. default statements will be handled if none of the other case
statements matches the switch variable.
3. b. The other descriptions are conditioner and confessional.
Activities
To improve your conditioning in terms of Java conditionals, review the topics
of this hour with the following activities:
Remove the break statement from one of the lines in the ClockTalk
program, and then compile it and see what happens when you run it. Try it again with
a few more break statements removed.
Create a short program that stores a value of your choosing from 1 to 100 in
an integer variable called grade. Use this grade variable with
a conditional statement to display a different message for all A, B, C, D, and F
students. Try it first with an if statement, and then try it with a switch
statement.