The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 115 C

CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes #22
Stuart C. Shapiro
Spring, 2007


Primitives Types & Related Issues 2: boolean

Booleans
Boolean types are truth values
The primitive Boolean type is boolean, and its wrapper class is java.lang.Boolean.
There are two boolean constant literals: true and false. The boolean operators are:
OperatorMeaning
&&logical and
||logical or
!logical not
==equals, or logical equivalence
!=not equals, or logical xor

Truth Tables for logical (boolean) operators:

pq ! p p && qp || q p == qp != q
truetruefalsetruetruetruefalse
truefalsefalsefalsetruefalsetrue
falsetruetruefalsetruefalsetrue
falsefalsetruefalsefalsetruefalse

Relational operators take numbers as arguments, and evaluate to boolean values. The relational operators are:

OperatorMeaning
<less than
<=less than or equal to
==equals
!=not equals
>=greater than or equal to
>greater than

The precedence order of operators, including numeric, relational, and boolean is:

unary +, unary -
*, /, %
+, -
<, <=, >, >=
==, !=
&&
||

The boolean operators use short-circuit evaluation.

Exercise/demo: write lt3(int x, int y, int z) to return true iff x < y < z.

== vs. equals
(The getClass() method is useful for seeing whether a variable's value is a primitive type or a wrapper object.)

5 == 5 --> true
new Integer(5).intValue() == new Integer(5).intValue() --> true
Integer.valueOf(5) == Integer.valueOf(5) --> true
new Integer(5) == new Integer(5) --> false
but
new Integer(5).equals(new Integer(5)) --> true

and similarly if you replace Integer with Boolean.

First Previous Next

Copyright © 2007 by Stuart C. Shapiro. All rights reserved.

Last modified: Fri Nov 9 08:59:58 EST 2007
Stuart C. Shapiro <shapiro@cse.buffalo.edu>