Difference between equals method and == operator in java
source link: http://adnjavainterview.blogspot.com/2023/09/difference-between-equals-method-and-operator-in-java.html.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Difference between equals method and == operator in java
In this post, we can discuss one of the important java interview questions i.e difference between equals() and == operator and sample examples.
The equals() method compares the content of two objects but == opeator checks the objects references of two objects for equality.
Let me see few examples to check both equals and == 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"); } } }
s1 equals s2 are equal s1 == s2 are not equal
- 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"); } } }
s1 equals s2 are equal s1 == s2 are equal
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK