Java: Boolean

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).

OpNameMeaning
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

OpNameMeaning
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

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.