boolean : Java Glossary

boolean
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.
// example boolean expressions
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.
// storing a boolean expression in a variable
boolean whether = x > 2;
// displaying a boolean variable on the console
System.out.println( whether );
You can use a boolean variable in an if later rather than
// referencing a boolean variable in an if
if ( whether ) makeDate();
if ( ! whether && done() ) finish();

boolean vs int

In C, booleans and ints are pretty well interchangeable.
// ILLEGAL IN JAVA!!  int is not the same as boolean
int seen = button.isVisible();
if ( seen ) doSomething();
// boolean must be used in Java where in C you could use an int.
boolean visible = button.isVisible();
if ( visible ) doSomething();

// or using an int with int-style syntax.
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
Don’t

Gotchas


CMP homejump to top You can get the freshest copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/boolean.html J:\mindprod\jgloss\boolean.html
logofeedback Please email your feedback for publication, letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email If you want your message kept confidential, not considered for posting, please explicitly specify that.
mindprod.com IP:[65.110.21.43]
view BlogYour face IP:[38.107.179.210]
You are visitor number 58,260.