Tuesday, May 6, 2014

What is the difference between equals() and == ?


Lets consider a library where we have a same book (say 'Java Programming') in two shelves. So book1 in shelf 1 and book2 in shelf2. Here book1 and book2 are nothing but two copies of the book (Java Programming)

Lets create book objects.

class Book{

String name;
String type;
public Book(String name) {
this.name=name;
}

@Override
public boolean equals(Object book2) {
return this.name.equals(((Book)book2).name);
}

}

Book book1 = new Book("Java Programming");
Book book2  = new Book("Java Programming");

Here in java the two book objects will be stored like this in memory.

     0x7aae62270  -> book1 -> Java Programming
     0x8aae62480   -> book2 -> Java Programming

equals() :
              book1.equals(book2) will return 'true' because their contents are same.

==
             book1 == book2 will return 'false' because they are located in two different locations.

So what happens when we change the above code like this :

Book book1 = new Book("Java Programming");
Book book2  = book1;

In memory :

     0x7aae62270  -> book1 -> Java Programming
     0x7aae62270  -> book2 -> Java Programming

equals() and ==  both returns true.





No comments:

Post a Comment