Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

HOUR 7:Using Conditional Tests to Make Decisions


Yo u u s e ifalong with the condition to test, as in the following statement:


if (account < 0) {
System.out.println(“Account overdrawn; you need a bailout”);
}


Theifstatement checks whether the accountvariable is below 0 by using
the less than operator <. If it is, the block within the ifstatement is run,
displaying text.


The block only runs if the condition is true. In the preceding example, if
theaccountvariable has a value of 0 or higher, the printlnstatement is
ignored. Note that the condition you test must be surrounded by parenthe-
ses, as in (account < 0).


The less-than operator <is one of several different operators you can use
with conditional statements.


Less Than and Greater Than Comparisons


In the preceding section, the <operator is used the same way as in math
class: as a less-than sign. There also is a greater-than conditional operator



, which is used in the following statements:



int elephantWeight = 900;
int elephantTotal = 13;
int cleaningExpense = 200;


if (elephantWeight > 780) {
System.out.println(“Elephant too fat for tightrope act”);
}


if (elephantTotal > 12) {
cleaningExpense = cleaningExpense + 150;
}


The first ifstatement tests whether the value of the elephantWeightvari-
able is greater than 780. The second ifstatement tests whether the
elephantTotalvariable is greater than 12.


If the two preceding statements are used in a program where
elephantWeightis equal to 600 and elephantTotalis equal to 10, the
statements within each ifblock are ignored.


Yo u c a n d e t e r m i n e w h e t h e r s o m e t h i n g i s l e s s t h a n o r e q u a l t o s o m e t h i n g
else with the <=operator. Here’s an example:

Free download pdf