• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparing Wrapper and Primitive (== and equals())

 
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

When comparing a Wrapper (say an Integer) and a primitive of a different type(anything other than int, say long), I seem to get a weird result. Normally == comparison is stricter because it compares the actual object vs equals which just compares for meaningful equality.

Please take a look at the following code:



This prints the following:-
== true

This doesn't make sense to me. The boxing that is going on here should be the same in both cases. So if == gives true, equals() should also give true.

Why is equals() method giving a false result here?

Thanks,
Nidhi
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nidhi Sar wrote:
Why is equals() method giving a false result here?



It is giving a false as the result because boxing a long primative yields a Long object -- and an Integer object is never equal to a Long object.

As for the comparison operator... when a comparison is done between a primative and a wrapper, unboxing the done with the wrapper -- meaning the comparison is done with primatives.

Henry
 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wow, so
with equals(), the primitive is boxed
with ==, the wrapper is unboxed

This is such a cool explanation! Is there any reason why this is inconsistent?
 
reply
    Bookmark Topic Watch Topic
  • New Topic