The relational operators you've learned so far (<
, <=
, >
,
>=
, !=
, ==
) are sufficient when you only need to check one
condition. However what if a particular action is to be taken only
if several conditions are true? You can use a sequence of if
statements to test the conditions, as follows:
if (x == 2) {
if (y != 2) {
System.out.println("Both conditions are true.");
}
}
This, however, is hard to write and harder to read. It only gets
worse as you add more conditions. Fortunately, Java provides an
easy way to handle multiple conditions: the logic operators. There
are three logic operators, &&
, ||
and !
.
&&
is logical and. &&
combines two boolean values and returns a boolean which is true if
and only if both of its operands are true. For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
||
is logical or. ||
combines two boolean
variables or expressions and returns a result that is true if
either or both of its operands are true. For instance
boolean b;
b = 3 > 2 || 5 < 7; // b is true
b = 2 > 3 || 5 < 7; // b is still true
b = 2 > 3 || 5 > 7; // now b is false
The last logic operator is !
which means not. It
reverses the value of a boolean expression. Thus if b
is true !b
is false. If b
is false
!b
is true.
boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b is true
These operators allow you to test multiple conditions more easily. For instance the previous example can now be written as
if (x == 2 && y != 2) {
System.out.println("Both conditions are true.");
}
That's a lot clearer.