Logical Operators & Short-Circuiting
Logical Operators & Short-Circuiting
In the previous lesson you learned how to write if / else if / else blocks. Real programs almost always need to check more than one condition at a time — for example, "is the user logged in and old enough?" or "did the network fail or did the server return an error?". Java gives you three logical operators to combine boolean expressions: &&, ||, and !.
The AND Operator: &&
&& produces true only when both operands are true. Think of it as "this AND that must hold."
If either side is false, the whole expression is false. The truth table:
true && true→truetrue && false→falsefalse && true→falsefalse && false→false
The OR Operator: ||
|| produces true when at least one operand is true. Think of it as "this OR that is enough."
true || true→truetrue || false→truefalse || true→truefalse || false→false
The NOT Operator: !
! flips a boolean value. It is a unary operator — it takes only one operand and inverts it.
if (!isNotEmpty). Rename the variable to isEmpty and write if (isEmpty). Code that reads like plain English is easier to maintain.
Short-Circuit Evaluation
This is one of the most important things to understand about && and ||. Java does not always evaluate both sides of a logical expression — it stops as soon as the result is determined.
- With
&&: if the left side isfalse, the result is alreadyfalse, so the right side is skipped. - With
||: if the left side istrue, the result is alreadytrue, so the right side is skipped.
This is not just an optimisation — it actively prevents errors. A classic example is guarding a null reference before using it:
If Java evaluated both sides regardless, name.isEmpty() would crash at runtime because name is null. Short-circuiting makes the guard pattern safe.
&&, put the null/bounds guard on the left so the risky operation on the right is only reached when it is safe to do so.
Combining Multiple Operators
You can chain several logical operators in one expression. Java evaluates ! first, then &&, then || (standard precedence). Use parentheses to make your intent explicit and avoid surprises:
a || b && c is parsed as a || (b && c) because && binds tighter than ||. When in doubt, add parentheses. They cost nothing and eliminate confusion.
Side Effects & Short-Circuiting
Because the right side may not run, avoid putting logic with side effects (like method calls that change state) inside a short-circuited condition unless you fully understand the implications:
This is rarely what you want. Keep conditions pure — compare values, do not modify state inside them.
Summary
The three logical operators let you build precise, compound conditions. && requires both sides; || requires at least one side; ! flips a value. Short-circuit evaluation means the right operand is skipped when the result is already known — use this to guard null references and array bounds, and always place the safest check first.