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.
boolean expressions
Anything you can put inside an if (…) is a
boolean expression e.g.
x > 2
0 <= y && y <= 10
! (0 <= y && y <= 10 )
button.isVisible()
A boolean expression evaluates to true
or false. You can store it in a boolean variable e.g.
boolean whether = x > 2;
You can print out a boolean variable. You don’t
need an if to do it.
System.out.println( whether );
You can use a boolean variable in an if
later rather than recalculating the expression.
if ( whether ) makeDate();
if ( ! whether && done() ) finish();
boolean vs int
In C, booleans and ints
are pretty well interchangeable. In Java they are totally separate types. You can’t
do the following in Java :
int seen = button.isVisible();
if ( seen ) doSomething();
You must write:
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 |.
Stuttering
Avoid goony expressions like:
if ( whether == true )
if ( whether == false )
if ( whether == true && done == false )
Don’t stutter, just write:
if ( whether )
if ( !whether )
if ( whether && !done )
Gotchas
- 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 brain.
- Use consistent variable and parameter names that make the convention obvious.