Web Analytics

Logical Operators

Beginner ~15 min read

Logical operators allow you to combine multiple boolean expressions. They are essential for creating complex conditions in your programs, like checking if a user is logged in AND has administrative privileges.

The 3 Logical Operators

Operator Name Description Example
&& Logical AND Returns true if both operands are true. (5 > 3) && (8 > 5) โ†’ true
|| Logical OR Returns true if at least one operand is true. (5 > 3) || (5 < 3) โ†’ true
! Logical NOT Reverses the boolean state. !(5 > 3) โ†’ false
Java Logical Operator Truth Tables
Output
Click Run to execute your code

Short-Circuit Evaluation

Java's logical operators are "short-circuiting." This means they stop evaluating as soon as the result is determined.

  • AND (&&): If the first operand is false, the result MUST be false. Java won't even evaluate the second operand.
  • OR (||): If the first operand is true, the result MUST be true. Java won't evaluate the second operand.

Why Short-Circuiting Matters

Consider this code:

if (object != null && object.callMethod()) { ... }

If object is null, the first check fails (false). Because of short-circuiting, Java never executes object.callMethod(). If it didn't verify the first part, this code would crash with a NullPointerException!

If you used a single & (bitwise AND), both sides would run, causing a crash.

Summary

  • && (AND): True only if ALL are true.
  • || (OR): True if ANY are true.
  • ! (NOT): Flips true to false, and vice versa.
  • Logical operators && and || short-circuit: they stop evaluation early if possible, which improves performance and safety.