Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boolean wrapper objects

 
Sachin Kapoor
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to K&B, == comparison for two Boolean wrapper objects returns true if they have same value (such as true)

But one question by Dan Chisholm doesn't conform this rule. This is the question:

Question 8

class B {
public static void main(String[] args) {
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
Boolean b3 = new Boolean("TrUe");
Boolean b4 = new Boolean("tRuE");
System.out.print((b1==b2) + ","); //line 5
System.out.print((b1.booleanValue()==b2.booleanValue()) + ",");
System.out.println(b3.equals(b4));
}}

What is the result of attempting to compile and run the program?
a. Prints: false,false,false
b. Prints: false,false,true
c. Prints: false,true,false
d. Prints: false,true,true
e. Prints: true,false,false
f. Prints: true,false,true
g. Prints: true,true,false
h. Prints: true,true,true
i. None of the above

And the answer by Dan Chisholm is (d): "false,true,true"

But shouldn't line 5 in above code print true because both Boolean wrapper objects are representing same value (true)?
 
christian combarel
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to K&B, == comparison for two Boolean wrapper objects returns true if they have same value (such as true)


More exactly, the comparison IF the wrappers are created through boxing :
Boolean b1 = true;
Boolean b2 = true;
b1 == b2 : true

But,
Boolean b3 = new Boolean(true);
Boolean b4 = new Boolean(true);
b3 == b4 : false
 
Sachin Kapoor
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic