| Author |
Boolean Wrappers?
|
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
|
|
Guys, This code below is from Dan Chisholm, How come it prints true for b1 == b2?? Confused.
|
SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
|
 |
Vinayagar Karpagam
Ranch Hand
Joined: Apr 09, 2006
Posts: 72
|
|
I believe the catch here is the valueOf(). When two wrappers are compared with ==, the references only are compared. b1 == b2 will be false when b1 = new Boolean(true) & b2 = new Boolean(true). But since valueOf() is used here, it gives the same object to both b1 & b2. Hope this helps.
|
 |
Sanjeev Singh
Ranch Hand
Joined: Nov 01, 2006
Posts: 381
|
|
All the Boolean objects (unless created with new operator)are same if there boolean value are same.So here all the references b1,b2,b3,b4 will retrun true when checked with == amongst themselfs. The same is true for Character(ascii from 0 to 127),Interger(-128 to 127)),Short,Byte.
|
~Sanjeev Singh<br />SCJP 1.5
|
 |
Sathishkumar Ethiraju
Greenhorn
Joined: Nov 23, 2006
Posts: 10
|
|
do you mean Integer i1 = Integer.valueOf("1"), i2 = Integer.valueOf("1"), i3 = Integer.valueOf("150"), i4 = Integer.valueOf("150") System.out.println(i1==i2); System.out.println(i3==i4); will result in true false i am getting false false
|
 |
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
|
|
The thing is that Integer.valueOf(String) always returns a new Integer while Boolean.valueOf(String) uses the constants Boolean.TRUE and Boolean.FALSE every time you invoke it. Therefore, Boolean.valueOf(String) always returns the same object. That is not the case of Integer.valueOf(String). Something similiar happens if you use Integer.valueOf(int), since the first 128 Integers are cached. In this case a and b are the same object, while c and d are different objects. [ December 21, 2006: Message edited by: Edwin Dalorzo ]
|
 |
 |
|
|
subject: Boolean Wrappers?
|
|
|