Java Boolean wrappers: evaluate == versus equals when constructed from case-varied strings, and compute the final result value. public class BoolTest { public static void main(String [] args) { int result = 0; Boolean b1 = new Boolean("TRUE"); Boolean b2 = new Boolean("true"); Boolean b3 = new Boolean("tRuE"); Boolean b4 = new Boolean("false"); if (b1 == b2) result = 1; // Line 10 if (b1.equals(b2)) result = result + 10; // Line 12 if (b2 == b4) result = result + 100; // Line 14 if (b2.equals(b4)) result = result + 1000; // Line 16 if (b2.equals(b3)) result = result + 10000; // Line 18 System.out.println("result = " + result); } }

Difficulty: Medium

Correct Answer: 10010

Explanation:


Introduction / Context:
This program checks subtle differences between reference equality (==) and value equality (equals) for Boolean wrapper objects created from String inputs, and it demonstrates that the String constructor for Boolean is case-insensitive for the literal "true".


Given Data / Assumptions:

  • b1 = new Boolean("TRUE") → value true.
  • b2 = new Boolean("true") → value true.
  • b3 = new Boolean("tRuE") → value true.
  • b4 = new Boolean("false") → value false.
  • result starts at 0; increments depend on equality checks.


Concept / Approach:
The Boolean(String) constructor yields true if the string (ignoring case) equals "true"; otherwise false. The operator == compares object references, not contained values, while equals compares the primitive boolean value inside the wrappers.


Step-by-Step Solution:
b1 == b2 → false (distinct objects) → result stays 0. b1.equals(b2) → true (true equals true) → result = 0 + 10 = 10. b2 == b4 → false → no change. b2.equals(b4) → false (true vs false) → no change. b2.equals(b3) → true (true vs true) → result = 10 + 10000 = 10010. Printed string is "result = 10010".


Verification / Alternative check:
Switch to Boolean.valueOf to see interning effects for certain paths; == may still not be reliable across distinct wrapper instances—always prefer equals for value comparison.


Why Other Options Are Wrong:
Values 0/1/10 ignore one or more equals checks; any other sum miscounts the lines that evaluate to true.


Common Pitfalls:
Assuming == compares content for wrappers; forgetting constructor case-insensitivity for "true".


Final Answer:
10010

More Questions from Java.lang Class

Discussion & Comments

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