Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

&& || !

Logical AND, OR and NOT for boolean values.

Available since: Java 1.0

Syntax

a && b  a || b  !a

Examples

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
true

Short-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 name

Notes

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

  • if / else — Runs a block of code only if a condition is true.
  • ? : — Picks one of two values by a condition — a short form of if-else.

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.