| Author |
Boolean class
|
putti don
Greenhorn
Joined: Jul 28, 2005
Posts: 20
|
|
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.
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
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 ]
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
 |
|
|
subject: Boolean class
|
|
|