• 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 construction(new/valueOf) - why different result?

 
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since a Boolean object can only have two values (true or false), and since there already exists the Boolean objects TRUE and FALSE, then why is everytime a boolean object is created using its constructor, a new object is created? Why not just do it the way the valueOf method does it - return a reference to Boolean.TRUE or Boolean.FALSE?
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the idea of "new" is to create new objects. If you would want to have the same object than it should be the same with strings as well. Why new String("aaa") creates an obejct (ok, actually two with the string literal) and new String("aaa") create another object. And they are different one.

Miki
 
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
new actually creates a new object regardless, but if you do String="aaa"; then it will check the String pool and use the same object if it exists. Don't know why Java was designed like this, but it is.
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, that's probably the reason.
I now realize that there are economical ways of creating objects. I guess this is one of the benefits when you study for SCJP.
Thanks.
 
reply
    Bookmark Topic Watch Topic
  • New Topic