What is the difference between equals() and == in Java?
Well equals() method and == operator both do the comparison operation and give us boolean output. But the difference is how they do the comparison.
== Operator:
The == operator has two ways of comparing objects/data.
when used with primitive data types like int, char, double.. etc, it just checks the data and returns true or false.
when used with objects/instances it doesn't compare the values, it compares the references of them. in short, It only checks that two variables are referencing the same memory address.
equals() method:
equals() method is a method hence it cannot be used for primitive datatypes. if you try to do so the compiler will tell you to do some core Java classes in Ameerpet, Hyderabad ๐คฃ.
equals() method is defined in the Object class which internally uses the == operator to compare the objects. see the below screenshot which shows the equals() method of the Object class.
So if the equals() method is not implemented, it will act as same as the == operator.
If we implement the equals() operator then we can write our own logic to compare both objects and return boolean.
let's take an example of a predefined Java class "String". See the below screenshot, the overridden equals method of the String class compares each character of the strings and if there is any mismatch it returns false.
Same way, we can override equals() method for classes created by us and write our own logic to compare objects.
Hopefully, you have understood the answer.......! โโโโโโ
Subscribe to my newsletter
Read articles from Hemant Besra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Hemant Besra
Hemant Besra
Experienced Full Stack Java developer. Have Strong Experience in JSP/Servlet, JSF, Jasper Report, Spring Framework, hibernate, Angular 5+, Microservices. Experienced in Front-end technologies such as HTML, CSS, JavaScript, angular 6+, AJAX, JSON, and XML. Strong Hands-on experience on working with Reactive Forms to build form-based application in Angular 6+.