Java booleans, wrapper Boolean, and the single ampersand operator: determine the output (JDK 1.6+).\n\npublic class BoolTest {\n public static void main(String[] args) {\n Boolean b1 = new Boolean("false");\n boolean b2;\n b2 = b1.booleanValue();\n if (!b2) {\n b2 = true;\n System.out.print("x ");\n }\n if (b1 & b2) { // single &: evaluates both sides\n System.out.print("y ");\n }\n System.out.println("z");\n }\n}

Difficulty: Easy

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

More Questions from Java.lang Class

Discussion & Comments

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