Here is a program that is almost the same as the BitLogic example shown earlier, but it
operates on boolean logical values instead of binary bits:
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println("
a = " + a);
System.out.println("
b = " + b);
System.out.println("
a|b = " + c);
System.out.println("
a&b = " + d);
System.out.println("
a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println("
!a = " + g);
}
}
After running this program, you will see that the same logical rules apply to boolean
values as they did to bits. As you can see from the following output, the string representation
of a Java boolean value is one of the literal values true or false:
a
=
true
b
=
false
a|b
=
true
a&b
=
false
a^b
=
true
a&b|a&!b
=
true
!a
=
false
Short-Circuit Logical Operators
Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as
short-circuit logical operators. As you can see from the preceding table, the OR operator
results in true when A is true, no matter what B is. Similarly, the AND operator results in
false when A is false, no matter what B is. If you use the || and && forms, rather than the
| and & forms of these operators, Java will not bother to evaluate the right-hand operand
when the outcome of the expression can be determined by the left operand alone. This is
very useful when the right-hand operand depends on the value of the left one in order
to function properly. For example, the following code fragment shows how you can take
advantage of short-circuit logical evaluation to be sure that a division operation will be valid
before evaluating it:
if (denom != 0 && num / denom > 10)
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home