Java Reference
In-Depth Information
A variable of type boolean can store the values true and false . Thus, you can set a
variable of type boolean equal to a Boolean expression. For example,
boolean madeIt = (time < limit) && (limit < max);
A Boolean expression can be evaluated in the same way that an arithmetic expression
is evaluated. The only difference is that an arithmetic expression uses operations such
as + , * , and / and produces a number as the final result, whereas a Boolean expression
uses relational operations such as == and < and Boolean operations such as && , || , and ! ,
and produces one of the two values true and false as the final result.
First, let's review evaluating an arithmetic expression. The same technique will work in
the same way to evaluate Boolean expressions. Consider the following arithmetic expression:
(number + 1) * (number + 3)
Assume that the variable number has the value 2. To evaluate this arithmetic
expression, you evaluate the two sums to obtain the numbers 3 and 5, and then you
combine these two numbers 3 and 5 using the * operator to obtain 15 as the final value.
Notice that in performing this evaluation, you do not multiply the expressions (number
+ 1) and (number + 3) . Instead, you multiply the values of these expressions. You use
3; you do not use (number + 1) . You use 5; you do not use (number + 3) .
The computer evaluates Boolean expressions the same way. Subexpressions are evaluated
to obtain values, each of which is either true or false . In particular, == , != , < , <= , and so
forth operate on pairs of any primitive type to produce a Boolean value of true or false .
These individual values of true or false are then combined according to the rules in
the truth tables shown in Display 3.5 . For example, consider the Boolean expression
truth tables
!( ( count < 3) || (count > 7) )
which might be the controlling expression for an if-else statement. Suppose the
value of count is 8. In this case, (count < 3) evaluates to false and (count > 7)
evaluates to true , so the preceding Boolean expression is equivalent to
!( false || true )
Consulting the tables for || (which is labeled “OR”), the computer sees that the
expression inside the parentheses evaluates to true . Thus, the computer sees that the
entire expression is equivalent to
!( true )
Consulting the tables again, the computer sees that !(true) evaluates to false , and
so it concludes that false is the value of the original Boolean expression.
The boolean Values Are true and false
true and false are predefined constants of type boolean . (They must be written in
lowercase.) In Java, a Boolean expression evaluates to the boolean value true when it is
satisfied, and it evaluates to the boolean value false when it is not satisfied.
 
Search WWH ::




Custom Search