Java programming — Boolean arrays, operator precedence (| vs &&), and short-circuit effects: class BoolArray { boolean [] b = new boolean[3]; int count = 0; void set(boolean [] x, int i) { x[i] = true; ++count; } public static void main(String [] args) { BoolArray ba = new BoolArray(); ba.set(ba.b, 0); ba.set(ba.b, 2); ba.test(); } void test() { if ( b[0] && b[1] | b[2] ) count++; if ( b[1] && b[(++count - 2)] ) count += 7; System.out.println("count = " + count); } }

Difficulty: Medium

Correct Answer: count = 3

Explanation:


Introduction / Context:
This evaluates Java operator precedence between | and &&, and the short-circuit behavior of && that can prevent evaluation (and side effects) on the right-hand operand.



Given Data / Assumptions:

  • After set calls: b[0] = true, b[2] = true, b[1] = false. count was incremented twice to 2.
  • First if mixes && and |; second if uses && with a side effect (++count) in the right operand's index.


Concept / Approach:
Precedence: the single bar | has higher precedence than &&, so b[0] && (b[1] | b[2]) is the effective grouping. Also, with &&, if the left side is false, the right side is not evaluated (short-circuit), so side effects there do not occur.



Step-by-Step Solution:

Initial state: count = 2; b = [true, false, true].First if: b[1] | b[2] = false | true = true; then b[0] && true = true; condition true, so count++ => count = 3.Second if: left side b[1] is false, so the right side b[(++count - 2)] is not evaluated due to short-circuit; count remains 3 and no addition of 7 occurs.Final print: "count = 3".


Verification / Alternative check:
Add parentheses explicitly to mirror precedence, and insert debug prints to confirm whether (++count - 2) runs.



Why Other Options Are Wrong:
They either miss the first increment, or assume the pre-increment in the second if executes despite short-circuiting.



Common Pitfalls:
Assuming && has higher precedence than | and forgetting that short-circuiting suppresses evaluation (and side effects) on the right.



Final Answer:
count = 3

More Questions from Operators and Assignments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion