Java's logical operators take boolean operands and produce a boolean. There are exactly three, and unlike the bitwise operators from the previous topic, none of them accept numbers.
| Operator | Name | Operands | Meaning |
|---|---|---|---|
&& | Logical AND | Two booleans | True only when both are true |
|| | Logical OR | Two booleans | True when at least one is true |
! | Logical NOT | One boolean | True when the operand is false |
boolean a = true;
boolean b = false;
System.out.println(a && b);
// false
System.out.println(a || b);
// true
System.out.println(!a);
// falseTwo compile errors are worth internalising, because they are the clearest way to see the difference from the bitwise family.
boolean p = true;
boolean q = true;
System.out.println(p ^ q);
// false, legal, this is the bitwise XOR on booleans
System.out.println(p & q);
// true, legal, the bitwise AND on booleans
System.out.println(!5);
// error: bad operand type int for unary operator '!'
System.out.println(~5);
// -6, legal, this is bitwise complement instead
System.out.println(p && 5);
// error: bad operand types for binary operator '&&'! negates truth, not bits. To flip the bits of a number you want ~, which is the subject of the unary operators topic.