Boolean Operations


So far, all the operations we have looked at have dealt with numbers. Now we turn our attention to operations that work on boolean data. Some of these operations share symbols with similar numeric operations (|, for example). However, the boolean versions are essentially different from their numeric counterparts.

Most of Java's boolean operations are binary, and both operands must be of boolean type.

And, Or, Exclusive Or, Inversion

We have already seen these as bitwise arithmetic operations. The symbols for and, or, and exclusive or are, as before, &, |, and ^, respectively. The symbol for inversion is ! rather than ~.

The following program prints out the results of applying these operators to true values:

public class BooleanOps {   public static void main(String[] args)   {     boolean a = true;     boolean b = true;     boolean x = a & b;     System.out.println("true&true = " + x);     x = a | b;     System.out.println("true|true = " + x);     x = a ^ b;     System.out.println("true^true = " + x);     x = !a;     System.out.println("!true = " + x);   } }

The output is

true&true = true true|true = true true^true = false !true = false

Boolean operations, like arithmetic operations, have precedence. The unary ! operator is evaluated before the binary &, |, and ^. For example, the value of !false|true is true, because !false is evaluated first. You can override the effects of precedence by using parentheses. In the current example, if you want the | operator to execute before !, use the expression !(false|true).

The BoolLab animated illustration demonstrates the evaluation of boolean expressions. Launch the program by typing java bool.BoolLab. Figure 3.10 shows the program just after it starts up.

click to expand
Figure 3.10: BoolLab: initial screen

You can type into the text field any valid expression composed of the variables a, b, and c, the literals true and false, the operators &, |, ^, and !, and parentheses. After you enter the expression you want, press Enter. The expression will appear in large font in the main area of the window. As with EvaluatorLab, you can click on the Run button to see an animation of the expression being evaluated. Click on Step to see an animation of just the next step in the expression's evaluation. The Run Lightspeed and Step Lightspeed buttons perform the evaluation immediately, without animation. Figure 3.11 shows the result of running the configuration of Figure 3.10.

click to expand
Figure 3.11: BoolLab after execution

Try the following expressions in BoolLab:

false | false | false | false | false | true true & true & false & true & true false & (((!(true ^true) & (false|true))|false)^false) true | (((!(false ^ false) & (true | false))| true)^ true)

The first expression shows that when you take the or of a number of values, a single true is enough to make the entire result true. The second expression shows that when you take the and of a number of values, a single false is enough to make the entire result false.

Now that you have seen Java's simple boolean operators, let's move on to the short-circuit operators, which shorten the time it takes to execute an operation. Before you read the next section, can you guess the point of the lengthy third and fourth expressions in the preceding code?

Short-Circuit Operators

This really happened to me, and perhaps it has happened to you. When I was a little boy, I was allowed to go out and play if I had made my bed and finished my homework. I didn't mind doing my homework, but I hated making my bed and often I wouldn't do it. When my mother asked if I had made my bed, I would start to say, "No, but I …" I was going to say that I had done my homework, but my mother would interrupt me. She was a busy person and she had heard all she needed to hear. Our agreement was that I would do two chores. As soon as she knew that I had not done one of those chores, there was nothing I could say about the other chore to convince her that I had lived up to my part of the agreement.

False & anything is false. When you compute x & y, and x is false, you don't have to spend any time at all on y. You already know the answer.

Consider the following expression, which you were invited to type into BoolLab in the previous section:

false & (((!(true ^true) & (false|true))|false)^false)

At first glance, this expression looks so complicated that you would not want to figure out its value in your head. But at second glance, once you realize that the expression's form is "false & anything," you don't have to look any further. The value is false, no matter what comes after the &.

Java provides an alternative to the & operator . It is called the short-circuit & operator, and its symbol is &&. The short-circuit version stops computing and immediately returns false if its first operand is false. Let's slightly modify the previous example:

false && (((!(true ^true) & (false|true))|false)^false)

Now the first operator is the short-circuit version. This expression evaluates to the same value as the previous version, but the evaluation takes less time because everything between the outermost parentheses is ignored.

There is also a short-circuit version of the | operator. Its symbol is ||, and it immediately returns true if its first operand is true.

The BoolLab animated illustration supports short-circuit operations. Launch the program again (type java bool.BoolLab), and see how it evaluates the following expressions:

false && (true|false) true && (true|false) false || && (true|false) true || && (true|false) 

Java's short-circuit operators allow you to profit from the principle that false-and-anything is false and true-or-anything is true. The amount of profit may seem trivial. In this example, the processing time that's saved by using && could not possibly be more than a microsecond or so. But a short-circuit expression might be executed not once but many times—even many millions or billions of times—so any time savings will be significant.

You will learn how to execute a single expression multiple times when you look at loops in Chapter 5. Moreover, the second operand of the short-circuit operator might be a call to a method that takes minutes or hours to execute. In this case, you definitely do not want to process the second operand unless you really have to. The next chapter will look at methods and method calling.

Now let's look at Java's comparison operators. These are binary operators whose operands can be numeric or boolean. The result type is always boolean.

Comparison Operations

Java's comparison operators always return a boolean value. Most of these operators work on numeric operands, but there are two that can take numeric or boolean operands. Table 3.2 summarizes the comparison operators.

Table 3.2: Comparison Operators

Operator

Meaning

Numeric Operands

Boolean Operands

==

Equals

3

3

!=

Does not equal

3

3

>

Is greater than

3

no

>=

Is greater than or equal to

3

no

<

Is less then

3

no

<=

Is less than or equal to

3

no

Note that the symbol for the equals comparison operator is a double equal sign (==), to distinguish it from the assignment symbol (=).

Comparison operators can be combined with other boolean operators. For example, assuming w, x, y, and z are variables of some numeric type, you might use the following expression:

w == x | y < z

Comparison operators have higher precedence than boolean operators, so the == and < comparisons happen before the | is evaluated. The example can be rewritten as follows:

(w == x) | (y < z) 

The parentheses make the expression clearer without changing the order of computation. Expressions such as this one are most often seen in flow-control statements, which allow you to execute blocks of code repeatedly, or only if certain desired conditions are met. We will look at flow-control statements in Chapter 5.




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net