4.2 Conditions and Logical Expressions | 155
that it is easiest for the computer to work with an-
swers that can be represented by the 1s and 0s of
the binary number system. For example, to ask, “Are
we having spinach for dinner tonight?” we would
say, “We are having spinach for dinner tonight.” If
the assertion is true, the answer to the question is
yes. If it is false, the answer is no.
Thus asking questions in Java means making an
assertion that is either true or false. The computer
evaluatesthe assertion, checking it against some in-
ternal condition (the values stored in certain vari-
ables, for instance) to see whether it is true or false.
The boolean Data Type
The booleandata type consists of just two values,
the constants trueand false. The reserved word
booleanis pronounced “bool-e-un.”^1 Boolean data is
used for testing conditions in code so that the computer can make decisions (as in a selec-
tion control structure).
We declare variables of type booleanin the same way that we declare variables of other
standard types—by writing the name of the data type and then an identifier:
booleandataOK; // True if the input data is valid
booleandone; // True if the process is done
booleantaxable; // True if the item has sales tax
Each variable of type booleancan contain one of two values: trueor false. It’s important
to understand right from the beginning that trueand falseare neither variable names nor
strings. Rather, they are special constants in Java and, in fact, are reserved words.
Logical Expressions
In programming languages, assertions take the form of logical expressions(also called Boolean
expressions). Just as an arithmetic expression is made up of numeric values and operations,
a logical expression is made up of logical values and operations. Every logical expression has
one of the two booleanvalues: trueor false.
Here are some examples of logical expressions:
A booleanvariable or constant
An arithmetic expression followed by a relational operator followed by an
arithmetic expression
A logical expression followed by a logical operator followed by a logical expression
Assertion
statement 1A statement 1B
true false
Figure 4.2 Selection (branching) Control Structure
(^1) The name booleanis a tribute to George Boole, a nineteenth-century English mathematician who de-
scribed a system of logic using variables with just two values, true and false. (See the May We Introduce
box on page 164.)