Aryan PrajapatKnowledge Contributor
What is the difference between the “==” operator and the “.equals()” method in Java?
What is the difference between the “==” operator and the “.equals()” method in Java?
The “==” operator checks for object reference equality, while the “.equals()” method checks for object value equality. For example, two different String objects with the same value will return true when compared using “.equals()”, but false when compared using “==”.
reference equality:
In Java, “==” is used for reference equality, which means that it checks whether two objects refer to the same memory location.
example of code:
String s1 = “hello”;
String s2 = new String(“hello”);
if (s1 == s2) {
System.out.println(“s1 and s2 are the same object”);
} else {
System.out.println(“s1 and s2 are different objects”);
}
output: s1 and s2 ar different objects.
value equality,equals() method:
Value equality takes place when two separate objects happen to have the same values or state.This compares values and is closely related to the Object’s equals() method.
example-
String s1 = “hello”;
String s2 = new String(“hello”);
if (s1.equals(s2)){
System.out.println(“s1 and s2 have the same value”);
} else {
System.out.println(“s1 and s2 have different values”);
}
output – s1 and s2 have same value.