Ask Questions?

View Latest Questions



Posted on: July 26, 2006 at 12:00 AM
The primitive type boolean has only two possible values: true and false.

Java Notes


The primitive type boolean has only two possible values: true and false.

Boolean literals - true and false

The two values are written with the reserved words true and false.

Booleans in control statements

The if, for, while, and do statements all require boolean values. Usually these are written as boolean valued expressions, using operators which produce boolean values.

Comparison operators

Comparison operators are used to compare two primitive values (rarely objects).

i < j less than6 < 24 is true.
i <= jless than or equal6 <= 24 is true.
i == j equal 6 == 24 is false.
i >= jgreater than or equal10 >= 10 is true.
i > j greater than10 > 10 is false.
i != j not equal 6 != 24 is true.

Logical operators

a && bandThe result is true only if both a and b are true.
a || b or The result is true if either a or b is true.
!a nottrue if a is false and false if a is true.

Other operators and methods returning boolean values

  • The instanceof operator.
  • Many methods return boolean values, eg, equals, and methods that begin with "is". If you are writing your own boolean method, starting the name with "is" is a good practice.
  • Less common logical operators: &, |, and ^ with boolean operands. These are generally used with bits. || (or) and && (and) are preferred to | and & because they are short-circuit operators that can stop the evaluation when one of the operands determines the resulting value.

Boolean variables

You can declare boolean variables and test them. For example, this simple bubble sort keeps looping until there were no exchanges, which means that everything must be sorted. This is only an example, not a good way to sort.

void bubbleSort(int[] x, int n) {
    boolean anotherPass;  // true if something was out of order
    do {
        anotherPass = false;  // assume everything sorted
        for (int i=0; i<n-1; i++) {
            if (x[i] > x[i+1]) {
                int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp; // exchange
                anotherPass = true;  // something wasn't sorted, keep going
    } while (anotherPass);

Not like C/C++

Unlike C/C++, Java does NOT allow an integer expression where false is a zero value and true is any non-zero value. This doesn't work in Java.

Copyleft 2004 Fred Swartz MIT License