File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Boolean Wrappers? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Boolean Wrappers?" Watch "Boolean Wrappers?" New topic
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 ]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Boolean Wrappers?
 
Similar Threads
valueOf()..
Boolean class
One more on wrapper classes from Dan's mock exam..
boolean question
valueOf()