Skip to main content

Command Palette

Search for a command to run...

What is the difference between equals() and == in Java?

Updated
β€’2 min readβ€’View as Markdown
What is the difference between equals() and == in Java?
H

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+.

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.

  1. when used with primitive data types like int, char, double.. etc, it just checks the data and returns true or false.

  2. 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.......! ✌✌✌✌✌✌

More from this blog

Java Blogs By Hemant: Expert Insights, Tips, and Tutorials for Java Developers

42 posts

Welcome to Java Blogs By Hemant! I'm Hemant, an IT professional having years of experience as Java Full Stack Developer.