This week's giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP and have Lucian Maly on-line!
See this thread for details.
Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Boolean class

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class C {
public static void main(String[] args) {
Boolean b1 = Boolean.valueOf(true);
Boolean b2 = Boolean.valueOf(true);
Boolean b3 = Boolean.valueOf("TrUe");
Boolean b4 = Boolean.valueOf("tRuE");
System.out.print((b1==b2) + ",");
System.out.print((b1.booleanValue()==b2.booleanValue()) + ",");
System.out.println(b3.equals(b4));
System.out.println(b3==b4);
}}

Answer is true,true,true,true.

My doubt is whether Boolean.valueOf(...) returns a new Boolean object? If yes, then why b1==b2 and b3==b4 are true.

Thanks.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you check the Boolean class' API you will see that there are two instances of the class Boolean that are "readymade". One is a wrapper for true and the other is a wrapper for false. One of these two instances is returned by all of the valueOf methods. That's why "b1 == b2" and "b3 == b4" are true in the example. In fact all of b1, b2, b3, b4 refer to the same wrapper object representing true.

Again referring to the API, if you really want a new Boolean instance, independent of the two readymade ones, you should use the Boolean constructor.
Boolean b5 = new Boolean(true). This results in a Boolean wrapper object such that b5 != b1 (or b2, b3, b4).

The API tells you all that and more besides.
[ September 23, 2005: Message edited by: Barry Gaunt ]
 
Liar, liar, pants on fire! refreshing plug:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic