File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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:

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

marc weber

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
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?

[ 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.

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707

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,
It is sorta covered in the JavaRanch Style Guide.
subject: equals and == with wrappers
Similar Threads
Wrapper Class Problem
doubt: equals&==
Using ==,equals with Wrappers and Strings Problem
Conditional Operator with different return types