Relational and Conditional Operators
A relational operator compares two values and determines the relationship between them. The table below summarizes Java's relational operators:
Operator Name Use Return true if
> Greater than x > y x is greater than y
>= Greater or equals x >= y x is greater than or equal to y
<>
<= Less than or equals x <= y x is less than or equal to y
== Equals x == y x and y are equal
!= Not equals x != y x and y are not equal
Relational operators often are used with the conditional operators to construct more complex decision-making expressions. One such operator is &&, which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The following line of CodeText uses this technique to determine if the value of x lies between 10 and 15,
if (x >= 10 && x <= 15)
In this instances, the second operand to a conditional operator is not evaluated if x = 5, because it does not matter whether the second condition is true or not as && only returns true when both conditions evaluate to true. In order for both operands to be evaluated regardless of the statement outcome, use another boolean and operator &. The operator & is similar to && if both of its operands are of boolean type. However, & always evaluates both of its operands and returns true if both are true.
The table below summarizes Java's conditional operators:
Operator (long name) Use Return true if
& (logical AND) x & y x and y are both true,
always evaluates x and y
&& (conditional AND) x && y x and y are both true,
conditionally evaluates op2
if x is true
(logical OR) x y either x or y is true,
always evaluates x and y
(conditional OR) x y either x or y is true,
conditionally evaluates op2
! (NOT) !x x is false
No comments:
Post a Comment