ptg7068951
WHAT YOU’LL LEARN IN
THIS HOUR:
.Using the ifstatement for
basic conditional tests
.Te s t i n g w h e t h e r o n e v a l u e
is greater than or less than
another
.Te s t i n g w h e t h e r t w o v a l u e s
are equal or unequal
.Usingelsestatements as
the opposite of ifstate-
ments
.Chaining several condition-
al tests together
.Using the switchstate-
ment for complicated con-
ditional tests
.Creating complicated tests
with the ternary operator
When you write a computer program, you provide the computer with a
list of instructions called statements, and these instructions are followed to
the letter. You can tell the computer to work out some unpleasant mathe-
matical formulas, and it works them out. Tell it to display some informa-
tion, and it dutifully responds.
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 computer should display this message
only if your account is overdrawn. If it isn’t, the message would be inaccu-
rate and emotionally upsetting.
The way to accomplish this task in a Java program is to use a conditional, a
statement thatcauses something to happen in a program only if a specific
condition is met. During this hour, you learn how to use the conditionals
if, else, and switch.
Whena Java program makes a decision, it does so by employing a condi-
tional statement. During this hour, you are checking the condition of sever-
al things in your Java programs using the conditional keywords if, else,
switch, case, and break. You also use the conditional operators ==, !=, <,
, <=, >=and ?, along with booleanvariables.
if Statements
The most basic way to test a condition in Java is by using an ifstatement.
The ifstatement tests whether a condition is true or false and takes action
only if the condition is true.
HOUR 7
Using Conditional Tests to Make
Decisions