Can you tell the difference between equals() method and equality operator (==) in Java? code example
Example 1: difference betweeen == and .equals() in java
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
true
Explanation:
We can use == operators for reference comparison (address comparison) and
.equals() method for content comparison. In simple words, == checks if both
objects point to the same memory location whereas .equals() evaluates to the
comparison of values in the objects.
Example 2: Difference between == operator and equals method in java
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2);
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));