Java Jem: Objects - "==" vs equals()

by Michael Thomas

(Tutorial Home Page)

by Michael Thomas

(Tutorial Home Page)

Topic Information
General The following information can be difficult to visualize, especially the topic "Strings created by Assignments".  You will want to study the example program along with this Java Jem.
Objects & == The == returns true if the variable reference points to the same object in memory.
Objects & equals() equals() - returns the results of running the equals method of that class.  If one does not exist then the inherited Object class' equals() method is run which evaluates if the references point to the same object in memory.  The Object.equals() works just like the "==" operator.
Strings created by Assignments Strings created by the new operator or created by Objects that return String objects following the statements presented in the above 2 topics: "Objects & ==" and "Objects & equals".  

However, Strings created by literal assignments follow its own rules.  An example of a literal assignment would be: String strMy = "Hello World";.  The following information can be difficult to visualize therefore you will want to study the example program at my Java certification site.

Rule for Strings created by literal assignments:

  • If the literal String assignment is identical to another String created by a literal assignment then a new String object is not created. A reference to an existing String, which was created by a literal assignment, is returned.