Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java string equals() method.

❮ String Methods

Compare strings to find out if they are equal:

Try it Yourself »

Definition and Usage

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

Tip: Use the compareTo() method to compare two strings lexicographically.

Parameter Values

Technical details.

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

How to Implement Java’s equals Method Correctly

how to make equals method in java

At SitePoint we’re always looking to expand the range of topics we cover. Lately, we’ve set our sights on exploring the world of Java. If you’re a strong Java developer who wants to contribute to our coverage, get in touch with a few ideas for articles you’d like to write.

A fundamental aspect of any Java class is its definition of equality. It is determined by a class’s equals method and there are a couple of things to be considered for a correct implementation. Let’s check ’em out so we get it right!

Note that implementing equals always means that hashCode has to be implemented as well! We’ll cover that in a separate article so make sure to read it after this one.

Identity Versus Equality

Have a look at this piece of code:

We have two strings and they are obviously different.

What about these two?

Here we have only one String instance and some and other both reference it. In Java we say some and other are identical and, accordingly, identical returns a Boolean value that is true .

What about this one?

Now, some and other point to different instances and are no longer identical, so identical is false. (We’ll ignore String interning in this article; if this bugs you, assume every string literal were wrapped in a new String(...) .)

But they do have some relationship as they both “have the same value”. In Java terms, they are equal , which is checked with equals :

Here, equals is true .

A variable’s Identity (also called Reference Equality ) is defined by the reference it holds. If two variables hold the same reference they are identical . This is checked with == .

A variable’s Equality is defined by the value it references. If two variables reference the same value, they are equal . This is checked with equals .

But what does “the same value” mean? It is, in fact, the implementation of the equals method in Java that determines “sameness”. The equals method is defined in Object and since all classes inherit from it, all have that method.

The default implementation used in Object checks identity (note that identical variables are equal as well), but many classes override it with something more suitable. For strings, for example, it compares the character sequence and for dates it makes sure that both point to the same day.

Many data structures, most notably Java’s own collection framework, use equals to check whether they contain an element.

For example:

The variable contains is true because, while the instances of "b" are not identical, they are equal.

(This is also the point where hashCode comes into play.)

Thoughts on Equality

Any implementation of equals must adhere to a specific contract or the class’s equality is ill-defined and all kinds of unexpected things happen. We will look at the formal definition in a moment but let’s first discuss some properties of equality.

It might help to think about it as we encounter it in our daily lives. Let’s say we compare laptops and consider them equal if they have the same hardware specifications.

  • One property is so trivial that it is hardly worth mentioning: Each thing is equal to itself. Duh.
  • There is another, which is not much more inspiring: If one thing is equal to another, the other is also equal to the first. Clearly if my laptop is equal to yours, yours is equal to mine.
  • This one is more interesting: If we have three things and the first and second are equal and the second and third are equal, then the first and third are also equal. Again, this is obvious in our laptop example.

That was an exercise in futility, right? Not so! We just worked through some basic algebraic properties of equivalence relations. No wait, don’t leave! That’s already all we need. Because any relation that has the three properties above can be called an equality.

Yes, any way we can make up that compares things and has the three properties above, could be how we determine whether those things are equal. Conversely, if we leave anything out, we no longer have a meaningful equality.

equality

The equals Contract

The equals contract is little more but a formalization of what we saw above. To quote the source :

The equals method implements an equivalence relation on non-null object references: It is reflexive : for any non-null reference value x , x.equals(x) should return true . It is symmetric : for any non-null reference values x and y , x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive : for any non-null reference values x , y , and z , if x.equals(y) returns true and y.equals(z) returns true , then x.equals(z) should return true . It is consistent : for any non-null reference values x and y , multiple invocations of x.equals(y) consistently return true or consistently return false , provided no information used in equals comparisons on the objects is modified. For any non-null reference value x , x.equals(null) should return false .

By now, the first three should be very familiar. The other points are more of a technicality: Without consistency data structures behave erratically and being equal to null not only makes no sense but would complicate many implementations.

Implementing equals

For a class Person with string fields firstName and lastName , this would be a common variant to implement string equals :

Let’s go through it one by one.

It is very important that equals takes an Object ! Otherwise, unexpected behavior occurs.

For example, assume that we would implement equals(Person) like so:

What happens in a simple example?

Then equal is true . What about now?

Now it’s false . Wat ?! Maybe not quite what we expected.

The reason is that Java called Person.equals(Object) (as inherited from the Object class, which checks identity). Why?

Java’s strategy for choosing which overloaded method to call is not based on the parameter’s runtime type but on its declared type. (Which is a good thing because otherwise static code analysis, like call hierarchies, would not work.) So if mrRobot is declared as an Object , Java calls Person.equals(Object) instead of our Person.equals(Person) .

Note that most code, for example all collections, handle our persons as objects and thus always call equals(Object) . So we better make sure we provide an implementation with that signature! We can of course create a specialized equals implementation and call it from our more general one if we like that better.

Equality is a fundamental property of any class and it might end up being called very often, for example in tight loops querying a collection. Thus, its performance matters! And the self check at the beginning of our implementation is just that: a performance optimization.

java if (this == o) return true;

It might look like it should implement reflexivity but the checks further down would be very strange if they would not also do that.

No instance should be equal to null, so here we go making sure of that. At the same time, it guards the code from NullPointerException s.

It can actually be included in the following check, like so:

Type Check and Cast

Next thing, we have to make sure that the instance we’re looking at is actually a person. This is another tricky detail.

Our implementation uses getClass , which returns the classes to which this and o belong. It requires them to be identical! This means that if we had a class Employee extends Person , then Person.equals(Employee) would never return true – not even if both had the same names.

This might be unexpected.

That an extending class with new fields does not compare well may be reasonable, but if that extension only adds behavior (maybe logging or other non-functional details), it should be able to equal instances of its supertype. This becomes especially relevant if a framework spins new subtypes at runtime (e.g. Hibernate or Spring), which could then never be equal to instances we created.

An alternative is the instanceof operator:

Instances of subtypes of Person pass that check. Hence they continue to the field comparison (see below) and may turn out to be equal. This solves the problems we mentioned above but opens a new can of worms.

Say Employee extends Person and adds an additional field. If it overrides the equals implementation it inherits from Person and includes the extra field, then person.equals(employee) can be true (because of instanceof ) but employee.equals(person) can’t (because person misses that field). This clearly violates the symmetry requirement.

There seems to be a way out of this: Employee.equals could check whether it compares to an instance with that field and use it only then (this is occasionally called slice comparison ).

But this doesn’t work either because it breaks transitivity:

Obviously all three instances share the same name, so foo.equals(fu) and foo.equals(fuu) are true . By transitivity fu.equals(fuu) should also be true but it isn’t if the third field, apparently the department, is included in the comparison.

There is really no way to make slice comparison work without violating reflexivity or, and this is trickier to analyze, transitivity. (If you think you found one, check again. Then let your coworkers check. If you are still sure, ping me . ;) )

So we end with two alternatives:

  • Use getClass and be aware that instances of the type and its subtypes can never equal.
  • Use instanceof but make equals final because there is no way to override it correctly.

Which one makes more sense really depends on the situation. Personally, I prefer instanceof because its problems (can not include new fields in inherited classes) occurs at declaration site not at use site.

Field Comparison

Wow, that was a lot of work! And all we did was solve some corner cases! So let’s finally get to the test’s core: comparing fields.

This is pretty simple, though. In the vast majority of cases, all there is to do is to pick the fields that should define a class’s equality and then compare them. Use == for primitives and equals for objects.

If any of the fields could be null, the extra checks considerably reduce the code’s readability:

And this already uses the non-obvious fact that null == null is true .

It is much better to use Java’s utility method Objects.equals (or, if you’re not yet on Java 7, Guava’s Objects.equal ):

It does exactly the same checks but is much more readable.

We have discussed the difference between identity (must be the same reference; checked with == ) and equality (can be different references to “the same value”; checked with equals ) and went on to take a close look at how to implement equals .

Let’s put those pieces back together:

  • Make sure to override equals(Object) so our method is always called.
  • Include a self and null check for an early return in simple edge cases.
  • Use getClass to allow subtypes their own implementation (but no comparison across subtypes) or use instanceof and make equals final (and subtypes can equal).
  • Compare the desired fields using Objects.equals .

Or let your IDE generate it all for you and edit where needed.

Final Words

We have seen how to properly implement equals (and will soon look at hashCode ). But what if we are using classes that we have no control over? What if their implementations of these methods do not suit our needs or are plain wrong?

LibFX to the rescue! (Disclaimer: I’m the author.) The library contains transforming collections and one of their features is to allow the user to specify the equals and hashCode methods she needs.

FAQs about the equals Method in Java

The equals method is used to compare the contents or values of objects in Java. It is commonly used to determine whether two objects are considered equal based on their attributes or properties.

The equals method is defined in the Object class, which is the root class for all Java classes. It has the following signature: public boolean equals(Object obj). Classes that need customized equality comparison should override this method.

To use the equals method, you call it on an object and pass another object as an argument. The method returns a boolean value indicating whether the two objects are equal based on the defined comparison logic.

To customize the behavior of the equals method for your own class, you need to override it in your class and provide your own implementation of the comparison logic that makes sense for the attributes of your class.

When implementing the equals method, you should consider: Providing a null check and checking if the objects are of the same class. Comparing each attribute that contributes to the equality of the objects. Adhering to the general contract of the equals method, which includes reflexivity, symmetry, transitivity, and consistency.

No, the equals method and the == operator have different purposes. The == operator compares object references, checking if two references point to the same memory location. The equals method, on the other hand, compares the contents or values of objects based on your custom logic.

Yes, you can override the equals method for classes that inherit from another class. If the parent class already has an overridden equals method, you might need to call the parent’s equals method within your own implementation to ensure complete comparison.

When comparing strings using the equals method, you should avoid using the == operator, as it checks reference equality. Instead, use the equals method to compare the actual content of the strings.

No, the equals method is not used to compare primitive data types like int, double, etc. For primitive types, you can directly use the equality operator (== and !=) for comparison.

Yes, it’s a good practice to override the hashCode method whenever you override the equals method. This ensures that objects that are considered equal produce the same hash code, which is important when using objects as keys in hash-based collections like HashMap.

  • Prev Class
  • Next Class
  • No Frames
  • All Classes
  • Summary: 
  • Nested | 
  • Field | 
  • Constr  | 
  • Detail: 

Class Object

  • java.lang.Object
  • public class Object Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Since: JDK1.0 See Also: Class

Constructor Summary

Method summary, constructor detail, method detail.

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0; Class<? extends Number> c = n.getClass();

x.clone() != x
x.clone().getClass() == x.getClass()
x.clone().equals(x)
getClass().getName() + '@' + Integer.toHexString(hashCode())
1000000*timeout+nanos

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .

Scripting on this page tracks web page traffic, but does not change the content in any way.

Javatpoint Logo

Java Method Class

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

How to use == operator and equals() method correctly in Java

In this post, we will see how to use the == operator and equals() method correctly in Java.

1. Overview of == operator and equals() method

The == is a relational operator in Java that is used to compare primitive types such as int, double, char, float, etc. We should not use it to compare two object references since for any non-null reference values x and y, x == y returns true only when x and y refer to the same object.

  The equals() method in the Object class is used to compare objects. It behaves similarly to the == operator if not overridden by a class. Every class should override the equals() method of the Object class and specify the equivalence relation on objects. The equivalence relation should be such that equals() methods evaluate the comparison of values in the objects irrespective of the two objects refer to the same instance or not. Since equal objects must have equal hash codes, it is necessary to override the hashCode() method.

2. How to use the == operator and equals() method correctly in Java?

The general rule of thumb is to use the == operator when we want to compare primitive types or references of objects, and use the equals() method when we want to compare the contents or states of objects. However, there are some exceptions and caveats that we should be aware of when using these operators and methods. Here are some tips and best practices that we should follow:

1. Using with complex expressions

Always use parentheses when using the == operator and equals() method with complex expressions or logical operators. This will avoid any confusion or ambiguity about the order of evaluation or precedence. For example:

2. Using with Strings

Always use equals() method when comparing strings or comparing other objects that override this method. Do not use == operator for comparing strings or other objects that override this method unless we are sure that we want to compare their references. This will avoid any unexpected or incorrect results due to different memory locations or implementations. For example:

3. Using with possible null objects

Always check for null values before using the equals() method. If we call the equals() method on a null reference, we will get a NullPointerException , which is a runtime exception that can crash our program. To avoid this, we should always check if the object is null before calling the equals() method. For example:

4. Using with Objects

Always override the equals() method and the hashCode() method together when creating our own classes. The hashCode() method is another method that is defined in the Object class, and it returns an integer value that represents the hash code of an object. The hash code is used by some data structures and algorithms, such as hash tables and sets, to store and retrieve objects efficiently. The contract between the equals() method and the hashCode() method is that if two objects are equal according to the equals() method, they must have the same hash code according to the hashCode() method. Therefore, if we override the equals() method in our class, we should also override the hashCode() method to ensure consistency and correctness.

Download    Run Code

That’s all about using the == operator and equals() method correctly in Java.

Rate this post

Average rating 5 /5. Vote count: 1

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

guest

What is equals() Method in Java?

Java Course - Mastering the Fundamentals

“==” operator and equals() method are the functionalities which are used to test equality between two variables in Java. By default, == operator compares the memory locations of objects pointed to by the reference variables.

The equals() method is defined in the Object class in Java. By default, it uses the == operator for comparison. However, equals() method can be overridden to provide custom logic to compare two objects.

Introduction

Let's assume that you are an instructor of a course and a few students have enrolled into your course. You are maintaining a database of students with few details like their enrollment number , name , courses in which they are enrolled and the percentage score. You want to find out all those students who have scored more than 90% score or you want to find out how many students have enrolled in Computer Science course.

Let's see how we would make use of the “==” operator or the equals() method to find out the details we require.

What is the equals() Method in Java?

When we want to compare two objects based on some logic, we need to override the equals() method in the corresponding class of those objects. Thus equals() methods compare two entities and return true if they are logically the same. Since equals() is a method defined in the Object class thus the default implementation of the equals() method compares the object references or the memory location where the objects are stored in the heap. Thus by default the equals() method checks the object by using the “==” operator.

Also, we need to override the hashCode() method if we are overriding the equals() method to avoid breaking the contract. If two objects when compared with the equals() method are equal then their hashCode must also be the same.

Default implementation of .equals() method defined in Object class

Let's see via an example by creating a Student class.

Now, let's define three students who have enrolled in some of the available courses.

Now if you want to find out all those students who have enrolled in Computer Science course, you would use equals() method like below.

Similarly you would compare other student's courseName . Why we are using equals() here? Because getCourseName() method returns a String object and equals() method of String class is overriden to compare the contents of the string and not object location as shown below.

Internal Implementation:

Let's see another example where we want to know if two Student objects are same or not. Let's see how we will override equals() method for Student class. The unique key to identify a student is enrollment number. So, two students are equal if they have same value of enrollmentNumber variable. Let's define three students as following:

Here, secondStudent and thirdStudent variables are equal because they have same enrollment number. Hence when we compare these two objects with equals() method, it should return true logically.

Let's see how will we override equals() method and hashCode() methods to achieve the same.

Override equals() method:

Explanation:

  • According to the implementation of hashCode() method, hashcode of all the three objects - firstStudent , secondStudent as well as thirdStudent comes out to be 5.
  • But first student is not same as second and third students as enrollmentNumber of the first student is different from both other objects.
  • According to the implementation of equals() method, secondStudent and thirdStudent objects are equal. This implies they should have same hashcode but vice-versa is not true.

Hashcode of two objects must be same if both objects are equal. However, if two objects have same hashcode, it does not imply those objects are equal.

What is the "==" operator in Java?

“==” operator is a binary equality operator used to compare the primitive data types in Java (like int, short, long, char, boolean, double, float and byte). It also compares the memory location or the references of the two objects stored in the heap memory.

Now if you have the same three students enrolled into the course as follows:

We would use == operator as mentioned below to check if some student have got 100% score

Interesting Example

Let's see another example, if we want to see that the second student and third student are enrolled in the same course, then == operator will not give the desired result.

  • This returns false as here the contents are not getting compared but the memory locations where these two String objects are stored are getting compared.
  • Since, these are two different String objects stored at different memory locations in the heap, hence it returns false .

Example of "==" vs equals() Method

Let's see how a "==" operator is used..

  • firstStudent and secondStudent point to Student objects stored in different memory locations.
  • firstStudent and firstStudentCopy point to the same Student object.
  • Both strings are not String objects but interned strings stored in a special memory space called String Pool. Strings with same value created using literals are stored in the String Pool at the same location. Read more .
  • Primitive variables are compared by their value using "==" operator by default.

Let's see how an equals() method is used

  • ".equals()" operator is not overridden in the code above, hence the default implementation provided in Object class is used.
  • According to the default implementation, if the reference variables point to the same object, output is true .
  • Primitive variables are compared by their value not memory location.

Difference between "==" and equals() Method in Java

  • == operator is a binary equality operator whereas equals() is a method defined in the Object class.
  • == operator compares the memory locations of two objects and returns a boolean value whereas equals() is used to compare the two objects by some business logic which can be defined.
  • Use == operator when you want to compare the values of two primitive data types or you want to compare two references are same or not. Use equals() method when you want to compare two objects by functionality.
  • == operator cannot be overridden in Java. However, equals() method can be overridden in a class. By default, the equals() method uses the == operator.

Comparing two objects with "==" and equals() method

Here, we are not overriding the equals() method. Hence, equals() method will use the default implementation in Object class to compare the object references.

Using Default Implementation of .equals() method

  • In the first comparison, we are comparing the memory locations using the equals() method, hence false.
  • Similar to the first comparison, but this time with == operator.
  • In the final comparison, we are comparing two objects pointing to the same Student object.

Overriding equals() Method in Student Class

In this code, we are overriding the .equals() method by specifying that two students shall be equal when they have same name and enrollment number. Hence we are writing some business logic by which our objects will be comparable.

firstStudent and secondStudent have different enrollmentNumber , hence false according to the implementation of equals() method. Similar logic is used for other comparisons as well. Use this Java Online Compiler to compile your code.

  • Use the “==” operator to compare the references of two objects.
  • Use the equals() method to compare the values of the two objects by a business logic or functionality.
  • equals() method has default implementation provided in Object class and compares the memory location of two objects if it's not overridden .
  • Remember to override hashcode() method defined in the Object class as well if you are overriding the equals() method. As if two objects are logically same then their hashCode should also be same whereas the vice-versa is not true.

Java Tutorial

  • Java Tutorial
  • Java - Home
  • Java - Overview
  • Java - Environment Setup
  • Java - Basic Syntax
  • Java - Variable Types
  • Java - Basic Datatypes
  • Java - Basic Operators
  • Java Control Statements
  • Java - Loop Control
  • Java - Decision Making
  • Java - If-else
  • Java - Switch
  • Java - For Loops
  • Java - For-Each Loops
  • Java - While Loops
  • Java - do-while Loops
  • Java - Break
  • Java - Continue
  • Object Oriented Programming
  • Java - Object & Classes
  • Java - Methods
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Polymorphism
  • Java - Overriding
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner classes
  • Java - Enums
  • Java Data Types
  • Java - Numbers
  • Java - Boolean
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Date & Time
  • Java - Math Class
  • Java File Handling
  • Java - Files
  • Java - Files and I/O
  • Java Error & Exceptions
  • Java - Exceptions
  • Java Multithreading
  • Java - Multithreading
  • Java Synchronization
  • Java - Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Thread Control
  • Java Networking
  • Java - Networking
  • Java - URL Processing
  • Java - Generics
  • Java Collections
  • Java - Collections
  • Java List Interface
  • Java - List Interface
  • Java - ArrayList
  • Java - Vector Class
  • Java - Stack Class
  • Java Queue Interface
  • Java - Queue Interface
  • Java - PriorityQueue
  • Java - Deque Interface
  • Java - LinkedList
  • Java -  ArrayDeque
  • Java Map Interface
  • Java - Map Interface
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - SortedMap Interface
  • Java - TreeMap
  • Java - The IdentityHashMap Class
  • Java Set Interface
  • Java - Set Interface
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - SortedSet Interface
  • Java - TreeSet
  • Java Data Structures
  • Java - Data Structures
  • Java - Enumeration
  • Java - BitSet Class
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Collection Interface
  • Java Miscellenous
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Documentation
  • Java Useful Resources
  • Java - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Java - equals() Method

Description.

The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.

Here is the detail of parameters −

  • Any object.

Return Value

The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.

This will produce the following result −

Kickstart Your Career

Get certified by completing the course

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

how to make equals method in java

  • Explore Our Geeks Community
  • Write an Interview Experience
  • Share Your Campus Experience
  • Difference between concat() and + operator in Java
  • Difference between Java and Core Java
  • Difference Between Source Code and Byte Code
  • Difference between Core Java and Advanced Java
  • new Operator vs newInstance() Method in Java
  • Difference between Javabeans and Enterprise Javabeans
  • Difference Between SAX Parser and DOM Parser in Java
  • How to Optimize String Creation in Java?
  • Difference between Anonymous Inner Class and Lambda Expression
  • Difference between Byte Code and Machine Code
  • Difference Between Equality of Objects and Equality of References in Java
  • String Literal Vs String Object in Java
  • Java - ForkJoinPool vs ExecutorService
  • Different ways for String to Integer Conversions in Java
  • How String Hashcode value is calculated?
  • Differences between PointToPoint and Publish/subscribe model in JMS
  • How to convert a String to an Int in Java?
  • Object Level Lock vs Class Level Lock in Java
  • Difference Between JavaEE and Spring

Difference between comparing String using == and .equals() method in Java

Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not. Whenever we create an object using the operator new, it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.

In general, both equals() and “==” operators in Java are used to compare objects to check equality, but here are some of the differences between the two: 

  • The main difference between the .equals() method and == operator is that one is a method, and the other is the operator.
  • 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.
  • If a class does not override the equals method , then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method. See Why to Override equals(Object) and hashCode() method? in detail.

Explanation: Here, we create two objects, namely s1 and s2. 

  • Both s1 and s2 refer to same objects.
  • When we use the == operator for s1 and s2 comparison, the result is true as both have the same addresses in the string constant pool.
  • Using equals, the result is true because it’s only comparing the values given in s1 and s2.

 Java String Pool

Let us understand both the operators in detail:

Equality operator(==)

We can apply equality operators for every primitive type, including the boolean type. We can also apply equality operators for object types. 

If we apply == for object types then, there should be compatibility between arguments types (either child to parent or parent to child or same type). Otherwise, we will get a compile-time error. 

Output:  

.equals() Method

In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false. 

Explanation: Here, we are using the .equals method to check whether two objects contain the same data or not. 

  • In the above example, we create 3 Thread objects and 2 String objects.
  • In the first comparison, we check whether t1 == t3 or not. As we know that both t1 and t3 point to the same object . That’s why it returns true.
  • In the second comparison, we are using the operator “==” for comparing the String Objects and not the contents of the objects. Here, both the objects are different, and hence the outcome of this comparison is “False.”
  • When we are comparing 2 String objects by .equals() operator, then we are checking that is both objects contain the same data or not.
  • Both the objects contain the same String, i.e., GEEKS. That’s why it returns true.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please Login to comment...

Similar read thumbnail

  • lakshmiprathyushaveturi
  • pranshupachouri
  • nishkarshgandhi
  • balaggarwal88
  • Java-Strings
  • Difference Between

Please write us at contrib[email protected] to report any issue with the above content

Improve your Coding Skills with Practice

 alt=

Java Guides

Java Guides

Search this blog.

Check out my 10+ Udemy bestseller courses and discount coupons: Udemy Courses - Ramesh Fadatare

Difference between == and equals() method in Java

1. introduction.

In Java, comparing objects and primitives is a fundamental operation. The == operator and the equals() method are two ways to compare objects, but they serve different purposes. The == operator compares references or primitive values, while the equals() method is intended for checking logical equality.

2. Key Points

1. == checks if two references point to the same object or if two primitives have the same value.

2. equals() is a method in the Object class that checks if two objects are logically equal.

3. equals() can be overridden in a class to define custom equality logic.

4. Using == with objects often leads to unexpected results if you're looking for logical equality rather than reference identity.

3. Differences

Explanation:.

1. The string literals example1 and example2 refer to the same object in the string pool, so == returns true .

2. object1 and object2 are created with new , so they reference different objects, and == returns false .

3. The equals() method checks the content of object1 and object2 , finds them identical, and returns true .

5. When to use?

- Use == to compare primitive values or when you need to check if two references point to the exact same object.

- Use equals() when you need to check if two objects are logically "equal", meaning they have the same content or state.

Post a Comment

Leave Comment

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

IMAGES

  1. Java String equals() and equalsIgnoreCase() Methods example

    how to make equals method in java

  2. String equalsIgnoreCase method in java with example

    how to make equals method in java

  3. How to Compare Two Objects with the equals Method in Java

    how to make equals method in java

  4. Java String equals() and equalsIgnoreCase() Methods example

    how to make equals method in java

  5. Learn Java equals() method with 5 Examples

    how to make equals method in java

  6. Java equals Method

    how to make equals method in java

VIDEO

  1. JAVA Proqramlaşdırma - String - 2

  2. How many claps I can make equals how many subs we get #subscribe

  3. Master Java String Comparison: Unlock the Power of the Equals Method in Under 60 Seconds!

  4. equality operators in java(in Hindi)

  5. 😳 What difference between equals() method & equality == operator #java #shorts #shortvideo

  6. Java for Testers

COMMENTS

  1. java

    1 Answer Sorted by: 3 This would be correct implementation of equals () in your case.

  2. Java String equals() Method

    Definition and Usage The equals () method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo () method to compare two strings lexicographically. Syntax public boolean equals(Object anotherObject) Parameter Values Technical Details String Methods

  3. How to Implement Java's equals Method Correctly

    String some = "some string"; String other = some; boolean identical = some == other; Here we have only one String instance and some and other both reference it. In Java we say some and other are...

  4. Method Class

    Practice The java.lang.reflect.Method.equals (Object obj) method of Method class compares this Method Object against the specified object as parameter to equal (object obj) method. This method returns true if the Method object is the same as the passed object.

  5. Overriding equals method in Java

    Overriding equals method in Java Read Discuss Practice Consider the following Java program: Java class Complex { private double re, im; public Complex (double re, double im) { this.re = re; this.im = im; } } public class Main { public static void main (String [] args) { Complex c1 = new Complex (10, 15); Complex c2 = new Complex (10, 15);

  6. Difference Between == and equals() in Java

    Overview In this tutorial, we'll describe two basic equality checks in Java - reference equality and value equality. We'll compare them, show examples, and highlight the key differences between them. Also, we'll focus on null checks and understand why we should use reference equality instead of value equality when working with objects. 2.

  7. Java

    Practice There are many ways to compare two Strings in Java: Using == operator Using equals () method Using compareTo () method Using compareToIgnoreCase () method Using compare () method Method 1: using == operator

  8. Equality in Java: Operators, Methods, and What to Use When

    Finally, always override hashCode() if you're overriding equals(). If two objects are equal (by the equals() method), then they must have the same hash code. That will ensure that they can be used, for instance, as keys on a HashMap. Java is one of the most popular programming languages ever, and that's not an easy feat.

  9. Java equals() and hashCode() Contracts

    Java SE defines the contract that our implementation of the equals() method must fulfill. Most of the criteria are common sense. The equals() method must be: reflexive: an object must equal itself; symmetric: x.equals(y) must return the same result as y.equals(x); transitive: if x.equals(y) and y.equals(z), then also x.equals(z); consistent: the value of equals() should change only if a ...

  10. Overriding hashCode() And equals() For Records

    A Java Object class has the equals() and hashCode() methods defined. Since all classes in Java inherit from the Object class, they have the default implementation of the methods as well.. The equals() method is meant to assert the equality of two objects, and the default implementation implies that if two objects are of the same identity, they're equal.

  11. equals() and hashCode() methods in Java

    Some principles of equals () method of Object class : If some other object is equal to a given object, then it follows these rules: Reflexive : for any reference value a, a.equals (a) should return true. Symmetric : for any reference values a and b, if a.equals (b) should return true then b.equals (a) must return true.

  12. Java String equals() method

    The Java String class equals () method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. The String equals () method overrides the equals () method of the Object class. Signature publicboolean equals (Object anotherObject) Parameter

  13. Java Integer equals() method with Examples

    The equals () method is a method of Integer class under java.lang package. This method compares the value of the parameter to the value of the current Integer object. It returns Boolean (True or False) which corresponds to the equality of this Integer and method argument object. It also overrides the equals () method of Object class.

  14. Object (Java Platform SE 8 )

    Indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references: . It is reflexive: for any non-null reference value x, x.equals(x) should return true.; It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

  15. How To Use .equals Method In Java

    Recommended Reading Java .equals () Method Java equals () method is a method of the Java Object class. This object class is the root of the class hierarchy in Java. i.e. every class in Java has class Object as its superclass. Hence, all objects and arrays implement the methods of this object class.

  16. Java Method equals() Method with Examples

    Parameter. obj - the reference object with which to compare.. Returns. true if these objects are same; false otherwise. Throw. No exception is thrown. Example 1

  17. How do I use the character's equals() method in Java?

    As the String is an object, you need to use the string.equals(string) method to confirm that the two strings are equal. However, why do you use the == to check if two chars are equal, char1 == char2, Stack Overflow. ... equals() is a method of all Java Objects. But char is not an Object type in Java, it is a primitive type, ...

  18. How to use == operator and equals() method correctly in Java

    4. Using with Objects. Always override the equals() method and the hashCode() method together when creating our own classes. The hashCode() method is another method that is defined in the Object class, and it returns an integer value that represents the hash code of an object. The hash code is used by some data structures and algorithms, such as hash tables and sets, to store and retrieve ...

  19. What is equals() Method in Java?

    Overview. "==" operator and equals () method are the functionalities which are used to test equality between two variables in Java. By default, == operator compares the memory locations of objects pointed to by the reference variables. The equals () method is defined in the Object class in Java. By default, it uses the == operator for ...

  20. Java

    The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.

  21. Difference between comparing String using == and .equals() method in Java

    Both equals () method and the == operator are used to compare two objects in Java. == is an operator and equals () is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.

  22. Difference between == and equals() method in Java

    The == operator compares references or primitive values, while the equals () method is intended for checking logical equality. 2. Key Points. 1. == checks if two references point to the same object or if two primitives have the same value. 2. equals () is a method in the Object class that checks if two objects are logically equal.