Java booleans, wrapper Boolean, and the single ampersand operator: determine the output (JDK 1.6+). public class BoolTest { public static void main(String[] args) { Boolean b1 = new Boolean("false"); boolean b2; b2 = b1.booleanValue(); if (!b2) { b2 = true; System.out.print("x "); } if (b1 & b2) { // single &: evaluates both sides System.out.print("y "); } System.out.println("z"); } }
-
Az
-
Bx z
-
Cy z
-
DCompilation fails.
-
Ex y z
Answer
Correct Answer: x z
Explanation
Introduction / Context: The task probes differences between primitive boolean and wrapper Boolean, the effect of booleanValue(), and the semantics of the single ampersand operator (&) in boolean expressions, which evaluates both operands but still returns a boolean result.
Given Data / Assumptions:
- b1 = new Boolean("false") so b1.booleanValue() is false.
- First if uses !b2, which is true because b2 is false.
- Single & is a non-short-circuit boolean operator.
- Output tokens have trailing spaces as shown.
Concept / Approach: After the first if block, b2 becomes true and "x " is printed. The second condition evaluates (b1 & b2) → (false & true) which is false, so the body is skipped. Finally, println prints "z" on the same line after a space from the previous print.
Step-by-Step Solution:
b1 = Boolean(false).b2 = b1.booleanValue() → false.if (!b2) → true → set b2 = true; print "x ".if (b1 & b2) → false & true → false → do not print "y ".println("z") → prints z, resulting in "x z".Verification / Alternative check: Replacing & with && would short-circuit, but the result would still be false for (false && true), producing the same printed tokens.
Why Other Options Are Wrong:
- z: Misses the earlier "x ".
- y z / x y z: The condition for y is false.
- Compilation fails: All types and methods are valid.
Common Pitfalls: Confusing & (non-short-circuit) with && (short-circuit); misunderstanding wrapper vs primitive behavior.
Final Answer: x z