← all problems

Compound Boolean Expressions: Precedence and Short-Circuit Evaluation 🌶️🌶️

Quick recap from the boolean-operators reference: ! (not), && (and), and || (or) combine boolean expressions, and evaluate in that precedence order — ! first, then &&, then || — the same way *// bind tighter than +/- in arithmetic.

One more behavior worth understanding closely: short-circuit evaluation. In a && b, if a is already false, the whole expression is guaranteed false no matter what b is — so Java never even evaluates b. Symmetrically, in a || b, if a is already true, the whole expression is guaranteed true, so b is never evaluated. This is not just a minor efficiency detail: if the skipped side has a side effect — like calling a method that prints something or changes a variable — that side effect might never actually happen.

1. Evaluate: true && false || true. Remember: && evaluates before ||.

2. Both expressions use the same three variables and the same operators -- only the parentheses differ. Fill in every row, then look for the rows where the two columns disagree. Why do they?

Fill in T or F for each row.

3. Predict first, then check. b++ is on the right of each && / ||, so it only runs when Java actually evaluates that side. Trace b, r1, r2, and r3 after each of lines 3-5 (a is 3 throughout).

int a = 3;int b = 10;boolean r1 = a > 5 && b++ > 0;boolean r2 = a < 5 && b++ > 0;boolean r3 = a < 5 || b++ > 0;

If a variable hasn't been declared, write DNE for Does Not Exist. If a variable has been declared but not initialized, write ?. Otherwise, fill in the value of each variable immediately after the labeled line finishes executing.

4. This is a classic guard: check that the divisor is safe BEFORE dividing. Type exactly what the last line prints.

int n = 10;int d = 0;boolean ok = d != 0 && n / d > 2;System.out.println(ok);

5. Same two conditions, opposite order. Java still evaluates left to right. If this program crashes, type the name of the exception it throws; if it prints something instead, type what it prints.

int n = 10;int d = 0;boolean ok = n / d > 2 && d != 0;System.out.println(ok);

6. Why might short-circuit evaluation matter beyond just saving a little computation time? Think about what could go wrong if the second half of an && or || has a side effect, like modifying a variable or printing something -- and what the guard in the last two questions was protecting against.

Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.