• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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 ]
 
We begin by testing your absorbancy by exposing you to this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic