Java Reference
In-Depth Information
This if statement contains two simple conditions. The condition gender == FEMALE com-
pares variable gender to the constant FEMALE to determine whether a person is female. The
condition age >= 65 might be evaluated to determine whether a person is a senior citizen.
The if statement considers the combined condition
gender == FEMALE && age >= 65
which is true if and only if both simple conditions are true. In this case, the if statement's
body increments seniorFemales by 1 . If either or both of the simple conditions are false,
the program skips the increment. Some programmers find that the preceding combined
condition is more readable when redundant parentheses are added, as in:
(gender == FEMALE ) && (age >= 65 )
The table in Fig. 5.15 summarizes the && operator. The table shows all four possible
combinations of false and true values for expression1 and expression2 . Such tables are
called truth tables . Java evaluates to false or true all expressions that include relational
operators, equality operators or logical operators.
expression1
expression2
expression1 && expression2
false
false
false
false
true
false
true
false
false
true
true
true
Fig. 5.15 | && (conditional AND) operator truth table.
Conditional OR ( || ) Operator
Now suppose we wish to ensure that either or both of two conditions are true before we
choose a certain path of execution. In this case, we use the || ( conditional OR ) operator,
as in the following program segment:
if ((semesterAverage >= 90 ) || (finalExam >= 90 ))
System.out.println ( "Student grade is A" );
This statement also contains two simple conditions. The condition semesterAverage >=
90 evaluates to determine whether the student deserves an A in the course because of a sol-
id performance throughout the semester. The condition finalExam >= 90 evaluates to de-
termine whether the student deserves an A in the course because of an outstanding
performance on the final exam. The if statement then considers the combined condition
(semesterAverage >= 90 ) || (finalExam >= 90 )
and awards the student an A if either or both of the simple conditions are true. The only
time the message "Student grade is A" is not printed is when both of the simple condi-
tions are false . Figure 5.16 is a truth table for operator conditional OR ( || ). Operator &&
has a higher precedence than operator || . Both operators associate from left to right.
 
Search WWH ::




Custom Search