Java Reference
In-Depth Information
is equivalent to
if
(number > 0)
System.out.println("The number is positive.");
else
System.out.println("The number is negative or zero.");
Of course, this is just a toy example. It is unlikely that anybody would use the first
of the preceding two examples, but you might use something like it if the value of
number
, and therefore the value of the Boolean expression, might change. For example,
the following code could (by some stretch of the imagination) be part of a program to
evaluate lottery tickets:
boolean
isPositive = (number > 0);
while
(number > 0);
{
System.out.println("Wow!");
number = number - 1000;
}
if
(isPositive)
System.out.println("Your number is positive.");
else
System.out.println("Sorry, number is not positive.");
System.out.println("Only positive numbers can win.");
true
and
false
Are Not Numbers
Many programming languages traditionally use 1 and 0 for
true
and
false
. The latest ver-
sions of most languages have changed things so that now most languages have a type like
boolean
with values for
true
and
false
. However, even in these newer language versions,
values of type
boolean
are automatically converted to integers and vice versa when context
requires it. In particular, C++ automatically makes such conversions.
In Java, the values
true
and
false
are not numbers, nor can they be type cast to any
numeric type. Similarly, values of type
int
cannot be type cast to
boolean
values.
TIP: Naming Boolean Variables
Name a
boolean
variable with a statement that will be
true
when the value of the
boolean
variable is
true
, such as
isPositive
,
pressureOK
, and so forth. That way
you can easily understand the meaning of the boolean variable when it is used in an
if-else
statement or other control statement. Avoid names that do not unambigu-
ously describe the meaning of the variable's value. Do not use names like
numberSign
,
pressureStatus
, and so forth.
■