How Equals and == Works in Java

The "Object" Class in Java provides a method with name "equals" which is used to test if two objects are equal. And the "==" is a operator. This operator when used for primitives, returns true if two primitive values are equal. And for Object references, this "==" operator returns true when they are referring to the same object.

The object "Object" which all other Java objects extend has an equals method which allows you to check to see if two objects are equal, which means you call equals on any object you want. Objet's implementation of equals does the following (
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values xand y, this method returns true if and only if x and y refer to the same object ( x==y has the value true ).
When you compare two instances using ==, you are actually comparing their memory addresses to see if they are references to the same object. This is usually not very useful in the normal course of programming. Whether an object is equal to another object is pretty context-specific, meaning that it depends on the types of objects that you are comparing.

Strings are a pretty straightforward case. If one string equals "abc" and another string equals "def", then if you check to see if they are equal by calling the equals method, it should return false. But if one string equals "abc" and the other string equals "abc", you don't want to compare the memory addresses of the two instances (since they will be different), but rather you want to compare the sequence of characters. Therefore, the String object override's Objet's equals method with it own implementation which simply compares the sequence of characters.
For example The following shows the use of equals() method


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
String s1 = new String("string1");
String s2 = new String("string1");
if (s2 == s1)
  System.out.print(">> We are EQUAL by ==");
else
  System.out.print(">> We are NOT EQUAL by ==");
if (s2.equals(s1))
   System.out.print(">> We are EQUAL by equals()");
else
System.out.print(">> We are NOT EQUAL by equals()");


will print the follwoing::
>> We are NOT EQUAL by == (**since we are comparing two string
object'sreference addresses)

>> We are EQUAL by equals() (** comparing the two string object's values)







Comments

  1. This is a good one , it cleared lots of doubt. But still the same holds for Java 6?

    ReplyDelete
  2. While discussing equals its important to know how to correctly override equals in Java because until you do it correctly you will confuse yourself.

    ReplyDelete

Post a Comment

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized