There are following difference between double equal(==) operator and equals() method in java.
Equals() method:—
equals() method compare the content value of two String object. this method is available in java.lang package.
- This method is only applicable for object reference but not for primitive.
- We can override equals() method for content comparison.
- If we are apply equals() method for heterogeneous object then we would get compile time or run time exception.
- To any object reference like m, m.equals(null) is always return false.
public class EqualityTest {
public static void main(String[] args) {
String s1 = new String("well");
String s2 = new String("well");
System.out.println(s1.equals(s2));
}
}
Output:- true
== Operator method :-
It is compare the reference value of two object.it return true when both object pointing to the same memory location.
- This operator is applicable for both primitive and object reference.
- We can not override ‘==’ operator for content comparison.
- If we are applying ‘==’ operator for heterogeneous object then we will get incompatible type exception.
- For ant object reference like h, h==null is always return false.
public class B {
String name;
B(String name) {
this.name = name;
}
}
public class EqualityTest {
public static void main(String[] args) {
B b1 = new B("well");
B b2 = new B("well");
System.out.println(b1 == b2);
String s1 = "test";
String s2 = "test";
System.out.println(s1 == s2);
}
}
Output:-
false
true
Above first output is false because b1 and b2 are two different object.
Second output is true because s1 and s2 String object is reference same object.