In this post, we will discuss one of the most common Java interview questions: the difference between the equals() method and the == operator. We will also explore practical examples to understand when and how each should be used.
The equals() method compares the contents (or logical equality) of two objects, whereas the == operator compares their object references to determine whether both references point to the same object in memory.
Let's look at a few examples to understand the difference between the equals() method and the == operator.
- Created two string objects using new operator and applied equals and == operator to check the equality.
public class DemoClass { public static void main(String[] args) { String s1 = new String("A"); String s2 = new String("A"); if (s1.equals(s2)) { System.out.println("s1 equals s2 are equal"); } else { System.out.println("s1 equals s2 are not equal"); } if (s1 == s2) { System.out.println("s1 == s2 are equal"); } else { System.out.println("s1 == s2 are not equal"); } } }
Output:-
s1 equals s2 are equal
s1 == s2 are not equal
Used new operator to create String objects and those objects will store in heap memory of JVM and will create two different objects in the heap even the contents are same. So == operator result will return false.
- Created two string objects using literal and applied equals and == operator to check the equality.
public class DemoClass { public static void main(String[] args) { String s1 = "A"; String s2 = "A"; if (s1.equals(s2)) { System.out.println("s1 equals s2 are equal"); } else { System.out.println("s1 equals s2 are not equal"); } if (s1 == s2) { System.out.println("s1 == s2 are equal"); } else { System.out.println("s1 == s2 are not equal"); } } }
Output:-
s1 equals s2 are equal
s1 == s2 are equal
Thank you for visiting blog.

No comments:
Post a Comment