Ans) == operator is binary operator used to compare the primitives and objects in java. Primitives such as int, float, boolean can use == to compare the values of primitive variables. But if == is used for comparing objects, then it compares the references of the object, == will return only true when two objects point to same memory location in JVM.
//implementation of String.class equals() method
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
It is advisable, to override the equals method( Why to override) in most of the user defined java objects.
String str1 = "MyName";
String str2 = "MyName";
String str3 = str2;
String str4 = new String("MyName");
str1 == str2 // true
str1 == str3 //true
str1 == str4 //false
str1.equals(str2) //true
str1.equals(str3) //true
str1.equals(str4) //true
The third case returns false , since new String("MyName") , create a new variable at different memory location.