The primitive type boolean
has only two possible
values: true
and false
.
The two values are written with the reserved words true
and false
.
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 are used to compare two primitive values (rarely objects).
Op | Name | Meaning |
---|---|---|
i < j | less than | 6 < 24 is true. |
i <= j | less than or equal | 6 <= 24 is true. |
i == j | equal | 6 == 24 is false. |
i >= j | greater than or equal | 10 >= 10 is true. |
i > j | greater than | 10 > 10 is false. |
i != j | not equal | 6 != 24 is true. |
Op | Name | Meaning |
---|---|---|
a && b | and | The 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 | not | true if a is false and false if a is true. |
instanceof
operator.equals
,
and methods that begin with "is". If you are writing your own boolean
method, starting the name with "is" is a good practice.
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); }
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.