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 equals and == with wrappers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals and == with wrappers" Watch "equals and == with wrappers" New topic
Author

equals and == with wrappers

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707


My question is, under what case we will get true while comparing two wrappers (ofcourse same), or one wrapper and one primitive.


Byte bb1 = 100; //Why isn't it giving error like, can't convert from int to Byte? While Line 1 and Line 2 are giving the same!!! :roll:


Thanks,
cmbhatt
[ April 15, 2007: Message edited by: Chandra Bhatt ]

cmbhatt
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See this topic in our SCJP FAQ.
[ April 15, 2007: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Thanks Marc,

But specifically my Question is regarding comparison between one primitive and
wrapper and using equals to compare two different wrappers.
How equals comparison is done?




Thanks,
cmbhatt
[ April 16, 2007: Message edited by: Chandra Bhatt ]
Omer Haderi
Ranch Hand

Joined: Sep 27, 2006
Posts: 42
hi there,

Byte bb1 = 100; works fine because 100 is in the range of the byte -128 to 127 if you change the value to 128 then you will get the same error.

As you already may know the signature of equals is


so you can pass any object there but the result will be false, because before equality the object is checked with the instanceof operator.

check specific implementations:


As of java 5 the primitives are autoboxed to Wrapper classes, so they are becoming objects.

Cheers,
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Omer,


Thanks for giving definition of the equals() for each wrapper. I was under impression that equals will return true if values are equal but I forgot the
"vital" instanceof test before bitwise comparison.


Thanks again,
cmbhatt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals and == with wrappers