• 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

equals()

 
Ranch Hand
Posts: 1491
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Float value1 = new Float(12);
Float value2 = new Float(12);

value1.equals(value2) returns true / false? (equals compares only String contents)
value1 == value2 returns true / false ? ( == compares object references)
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are you asking? What happens when you run it?
 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What have you tried? Have you looked in the Java™ Language Specification about caching values? Did you see whether that applies to Float? Is there any evidence that th Float has a String in it anywhere?
 
Sheriff
Posts: 3063
12
Mac IntelliJ IDE Python VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
== compares references and equals() compares values. If you don't understand the difference between references and values, then learning that is your first job. While it's possible to code in Java without clearly understanding references, I don't think it's really possible to do it well.

Somewhat complicating the issue is that the default implementation of equals() just compares references, so it does exactly what == does. However, Integers override that behavior, and instead compare the integer values, so even two Integer objects with different references will be equal according to equals() if they contain the same value.

Further complicating the issue is that Java's compiler tries to optimize memory usage. It will sometimes recognize that two Integers contain the same value and so can share a reference. In those cases, the == test will return true even though it seems you are comparing two different objects. It is because Integers are immutable that the compiler can safely make this optimization.



 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic