&& || !
Logical AND, OR and NOT for boolean values.
Available since: Java 1.0
Syntax
a && b a || b !aExamples
Combining conditions:
void main() {
int age = 25;
boolean member = false;
IO.println(age >= 18 && age <= 65);
IO.println(age < 12 || member);
IO.println(!member);
}Output:
true
false
trueShort-circuit evaluation — the right side is skipped when the answer is already known:
void main() {
String name = null;
if (name != null && name.length() > 3) {
IO.println("long name");
} else {
IO.println("no long name");
}
}Output:
no long nameNotes
Thanks to short-circuit evaluation, the name != null check protects name.length() from a NullPointerException. Single & and | on booleans always evaluate both sides, and on integers they are bitwise operations.
See also
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.