Unit 04 · lesson
Short Circuiting Can Protect a Boundary
Java's && and || do not always evaluate both sides.
That behavior is called short-circuit evaluation.
For &&, if the left side is false, the full expression cannot become true, so Java does not need to evaluate the right side.
For ||, if the left side is true, the full expression is already true, so Java does not need to evaluate the right side.
Why this matters
Suppose a program has text that may be null:
String command = null;
This is unsafe:
boolean start = command.equals("start");
Calling an instance method through a null reference causes a runtime failure.
Now consider:
boolean start = command != null && command.equals("start");
If command != null is false, Java does not evaluate the method call on the right.
The first condition guards the second operation.
Order is part of safety
Reverse it:
command.equals("start") && command != null
The null check arrives too late. Java has already tried to call .equals.
Same boolean pieces, different evaluation order, different runtime behavior.
Guard a denominator
Short circuiting can also protect numeric operations:
int total = 0;
int passed = 0;
if (total != 0 && (double) passed / total >= 0.7) {
IO.println("passing rate");
}
The division is skipped when total == 0.
But do not confuse "avoided an exception" with "handled the domain problem." A total of zero may need a visible NO DATA state rather than silently producing no output.
A clearer program may be:
if (total == 0) {
IO.println("NO DATA");
} else if ((double) passed / total >= 0.7) {
IO.println("passing rate");
} else {
IO.println("below target");
}
Short circuiting is a tool, not an excuse to hide invalid states.
Build a boundary test
Use this supplied state model:
String user = null;
boolean systemReady = true;
Write a condition that should only accept a non-null, nonblank user when the system is ready.
Test:
null;"";" ";"maya"with system ready;"maya"with system not ready.
For each test, predict which subexpressions Java must evaluate.
Evidence
Create one short-circuit expression where the left operand deliberately protects an operation on the right. Then:
- explain the evaluation order;
- show the boundary input that would fail without the guard;
- reverse the operands and predict the new behavior before running it;
- restore the safe version;
- state whether the guarded condition should silently return false or whether the program needs a separate invalid-state branch.
The strongest answer distinguishes preventing an unsafe operation from deciding what the application should do about bad state.