• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Boolean wrapper objects

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)?
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the explanation
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic