Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.

In Java, these statements must be written like this:

if(done == 0) ... // This is Java-style.
if(done != 0) ...

The reason is that Java does not define true and false in the same way as C/C++. In C/C++,
true is any nonzero value and false is zero. In Java,trueandfalseare nonnumeric values that
do not relate to zero or nonzero. Therefore, to test for zero or nonzero, you must explicitly
employ one or more of the relational operators.

Boolean Logical Operators


The Boolean logical operators shown here operate only onbooleanoperands. All of the
binary logical operators combine twobooleanvalues to form a resultantbooleanvalue.

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unar y NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternar y if-then-else

The logical Boolean operators,&,|, and^, operate onbooleanvalues in the same way
that they operate on the bits of an integer. The logical!operator inverts the Boolean state:
!true == falseand!false == true. The following table shows the effect of each logical operation:

A B A | B A & B A ^ B !A

False False False False False True
True False True False True False
False True True False True True
True True True True False False

Chapter 4: Operators 71

Free download pdf