This week's book giveaway is in the Functional programming forum.
We're giving away four copies of A Functional Approach to Java: Augmenting Object-Oriented Java Code with Functional Principles and have Ben Weidig on-line!
See this thread for details.
  • 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Peter Rooke
  • Himai Minh
Bartenders:
  • Piet Souris
  • Mikalai Zaikin

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 ]
 
moose poop looks like football shaped elk poop. About the size of this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic