Java Reference
In-Depth Information
table 5-1: Control Operators for Primitive Data Types
oper ator
Java synta x
english eQuivalent
x == y
x != y
Equality
Is x equal to y ?
Is x not equal to y ?
Relational
x < y
x <= y
x > y
x >= y
Is x less than y ?
Is x less than or equal to y ?
Is x greater than y ?
Is x greater than or equal to y ?
Logical
x && y
x || y
!x
Are x and y both true?
Is x , y , or both true?
Is x false?
Logical operators, on the other hand, are specific to Booleans, and are used to combine or negate
one or more conditions. There are three logical operators: AND ( && ), OR ( || ), and NOT ( ! ). If two
or more Boolean operands are joined using the AND operator, all must evaluate to true for the
overall expression to evaluate to true . If they are joined using the OR operator, at least one of them
must evaluate to true in order for the overall expression to evaluate to true . Finally, if the NOT
operator precedes a Boolean operand that evaluates to true , the overall expression will evaluate to
false and vice versa. It evaluates as the opposite of the original expression.
Truth tables are used in logic to show the outcome of Boolean operators on pairs of statements. In
the first two columns are two statements that can be true or false . In the columns that follow,
operators are listed with their results based on whether the statements are true or false . Table 5-2
is a truth table demonstrating the Boolean operators discussed here—namely NOT, AND, and OR.
table 5-2: Boolean Operator Truth Table
p
Q
!p
not p
p && Q
p and Q
p || Q
p or Q
TRUE
TRUE
! TRUE =FALSE
True AND True = TRUE
True OR True = TRUE
TRUE
FALSE
True AND False = FALSE
True OR False = TRUE
FALSE
TRUE
! FALSE =TRUE
False AND True = FALSE
False OR True = TRUE
FALSE
FALSE
False AND False = FALSE
False OR False = FALSE
In fact, you probably encounter these kinds of logical operators in your everyday life. For example, a
public transit system might follow a certain schedule if the day is Saturday OR a holiday and another
schedule otherwise. In other words, if (day == Saturday || day == holiday) , then follow the
weekend schedule. Then it is understood that if it is Saturday or a public holiday or both, the entire
statement is true . On the other hand, you might have a rule that states if a person is over 60 years old
AND they possess a bus card, then their fare is reduced, or if (age > 60 && busCard == true) ,
Search WWH ::




Custom Search