![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |
A relational operator compares two values and determines the relationship between them. For example,!=
returnstrue
if the two operands are unequal. This table summarizes Java's relational operators:
Operator Use Returns true
if>
op1 > op2
op1
is greater thanop2
>=
op1 >= op2
op1
is greater than or equal toop2
<
op1 < op2
op1
is less thanop2
<=
op1 <= op2
op1
is less than or equal toop2
==
op1 == op2
op1
andop2
are equal!=
op1 != op2
op1
andop2
are not equalRelational 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 code uses this technique to determine if an array index is between two boundaries. It determines if the index is both greater than 0 and less thanNUM_ENTRIES
(which is a previously defined constant value):Note that in some instances, the second operand to a conditional operator may not be evaluated. Consider this code segment:0 < index && index < NUM_ENTRIESThe(numChars < LIMIT) && (...)&&
operator will return true only if both operands are true. So, ifnumChars
is greater thanLIMIT
, the left-hand operand for&&
is false and the return value of&&
can be determined without evaluating the right-hand operand. In such a case, Java will not evaluate the right-hand operand. This has important implications if the right-hand operand has side effects such as reading from a stream, updating a value, or making a calculation.The operator
&
is similar to&&
if both of its operands are of boolean type. However,&
always evaluates both of its operands and returnstrue
if both aretrue
. Likewise,|
is similar to||
if both of its operands are boolean. This operator always evalutes both of its operands and returnsfalse
if they are bothfalse
.Java supports five binary and one unary conditional operators, shown in the following table:
Operator Use Returns true
if&&
op1 && op2
op1
andop2
are bothtrue
, conditionally evaluatesop2
||
op1 || op2
either op1
orop2
istrue
, conditionally evaluatesop2
!
! op
op
isfalse
&
op1 & op2
op1
andop2
are bothtrue
, always evaluatesop1
andop2
|
op1 | op2
either op1
orop2
istrue
, always evaluatesop1
andop2
^
op1 ^ op2
if op1 and op2 are different--that is if one or the other of the operands is true but not both
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |