# Java Notes

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

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

## Logical operators

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

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