Difference Between == & equals()


This is one of the frequently asked question in Interview.

== always checks for reference equality.Means If  2 references points to same Object == gives you true
equals() is a method available in java.lang.Object class and this method is overrided by many child class including String.
Note:-
If somebodys asks you,the differences between == and equals(),You should reverse question them for clearity,If he is talking about java.lang.Object.equals() or some other class equals()
There is no difference between == and equals() of Object class. equals() of Object class internally uses == operator for comparing the object reference.
source code of java.lang.Object class
public class Object
{
public boolean equals(Object obj) {
 return (this == obj);
    }
}
equals() of String class checks if the string content is equal or not(case-sensitive)
String s1=”hello”;
String s2=”hello”;
s1.equals(s2);//gives true. Since it is string pooling,only 1 object will  be created and shared by all reference(s1,s2)
s1==s2;  //also gives true,because only 1 object was created

String s1=”hello”;
String s2=new String(“hello”);
//2 new objects are created,so == gives false,where as equals() gives true

Comments

Popular posts from this blog

How to know which liferay version we are using

Viewing the SQL Query in liferay : debugging the SQL Query in Hibernate

Executing the BackGround Task