• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

all doubts about == and equals

Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
there has been tremendous number of posts regarding the differences effects between == and equals. Comparing this and that returns true? or false? why?

can you, as expertised in SCJP or general java knowledge, provide a summary of using == and equals and the approach working out the result?

there has been a lot of helpful users providing excellent explanation, but there are too all over posts.

pls help all starters like me!
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll give it a try...

The concept to keep in mind is that == is a simple comparison of values.
  • For primitives, values are straightforward (see note below regarding NaN).
  • For objects, the "values" are references to the instances. So in comparing objects using ==, the result will be true if and only if the instances are the same.
  • There are special cases in which the same instance is "re-used." For example, the String literal pool (see Strings Literally) and autoboxed wrappers of booleans or non-floating values within the range of -128 through 127 (see JLS - 5.1.7).

    The Object class implements equals as a comparison of instances (like ==). Therefore, if equals is not overridden, then this is the default implementation. Otherwise, how equals works depends entirely on how it's implemented for a specific type.

    Note: Equality testing of the primitive NaN (not a number) always results in false. The only exception is NaN != NaN, which returns true.
    For my next feat, I will require a volunteer from the audience! Perhaps this tiny ad?
    Garden Master Course kickstarter
      Bookmark Topic Watch Topic
    • New Topic