boolean : Java Glossary
©1996-2017 Roedy Green of Canadian Mind Products
Java has a logical type that can only have the values true or false called boolean. The boolean type deals with
only a single bit at a time. An immutable object wrapper around a boolean is called a Boolean. You can do
boolean operations on ints
or longs, many bits at a time using &, |, ^ and ~. With boolean, you can only process one bit at a time, typically with
!, && and
||. For bit strings longer than 64 bits, use java. util. BitSet. Even experienced
programmers sometimes lapse into redundant newbie-like baby talk when using booleans.
To avoid that embarrassement see newbie.
Anything you can put inside an
if (…) is a boolean expression e.g.
x > 2
0 <= y && y <= 10
! (0 <= y && y <= 10 )
A boolean expression evaluates to true or false. You can store it in a
boolean variable e.g.
boolean whether = x > 2;
out.println( whether );
You can use a boolean variable in an if later rather than
if ( whether ) makeDate();
if ( ! whether && done() ) finish();
boolean vs int
In C, booleans
and ints are pretty well interchangeable.
int seen = button.isVisible();
if ( seen ) doSomething();
boolean visible = button.isVisible();
if ( visible ) doSomething();
int seen = button.isVisible() ? 0 : 1;
if ( seen != 0 ) doSomething();
& vs && and | vs ||
&& and || are sometimes
called short circuit & and | or McCarthy & and |.
- You can drive yourself crazy writing Java programs using booleans to represent pairs of states in a program i.e. busy vs active, ok
vs error, Comparable vs Comparator, ascending vs descending where there is no
blindingly obvious convention about which of the pair should be true and which false. The
convention will not be obvious scaning the code. All you will see are
trues and falses. It is
very easy to accidentally reverse the convention on a method expecting the
opposite convention. The compiler will not warn you. If you get a program half
one convention and half the other you will have one heck of a time sorting it all
out. What to do?
- Use enums instead. You can hide the convention
inside the enum and use boolean getters with
names like isAscending and isDescending on enum constants
with names like ASCENDING and DESCENDING.
- Using named static final boolean constants
helps a little.
- Make up some crazy mnemonic about which is which that will stick in your
- Use consistent variable and parameter names that make the convention