File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Boolean wrapper objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Boolean wrapper objects" Watch "Boolean wrapper objects" New topic
Author

Boolean wrapper objects

Sachin Kapoor
Greenhorn

Joined: Jul 01, 2007
Posts: 19
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

Joined: Aug 04, 2007
Posts: 47
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



-------------
Chris
Sachin Kapoor
Greenhorn

Joined: Jul 01, 2007
Posts: 19
Thanks for the explanation
 
Don't get me started about those stupid light bulbs.
 
subject: Boolean wrapper objects