• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

.equals and == in Integer/Double

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

For Integer class, if I compare 2 objects with == , it compares the values of the object, but for Double,it compares only the location of the objects rather than values.
I can overcome in Double object by overriding .equals method. But my question is though both Integer/Double are classes and both implement .equals, why == works fine for Integer object and not for Double.
Any ideas?


 
Sheriff
Posts: 22682
128
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When a primitive is auto-boxed, it actually calls the valueOf method of the matching wrapper class. For integer types (byte, short, int, long), values from -128 to 127 (inclusive) are usually cached. That means that you can use == to compare them for these values. Other values will fail however; just try it with 128.

For float and double, there is no such caching (because there are simply waaaaayyyyy too many values). That means that each auto-boxed value will be a new object, and those do not compare well with ==.


The best strategy is too simply not use == when any object type is involved, but instead use the equals method (or Objects.equals to be null-safe).
 
Don't mess with me you fool! I'm cooking with gas! Here, read this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic