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

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Nicolai Parlog

How to Implement Java’s equals Method Correctly

Share this article

How to Implement Java’s equals Method Correctly

Identity Versus Equality

Thoughts on equality, the equals contract, implementing equals, final words, faqs about the 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.

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

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

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.

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.

What is the purpose of 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.

How is the equals method defined in Java?

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.

How do I use the equals method to compare objects?

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.

How can I customize the equality comparison using the equals method?

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.

What should I consider when implementing the equals method?

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.

Is the equals method the same as the == operator?

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.

Can I override the equals method for classes that inherit from another class?

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.

What is the recommended approach to comparing strings using the equals method?

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.

Can I compare primitive data types using the equals method?

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.

Should I always override the hashCode method when overriding equals?

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.

Nicolai is a thirty year old boy, as the narrator would put it, who has found his passion in software development. He constantly reads, thinks, and writes about it, and codes for a living as well as for fun. Nicolai is the former editor of SitePoint's Java channel , writes The Java 9 Module System with Manning, blogs about software development on codefx.org , and is a long-tail contributor to several open source projects. You can hire him for all kinds of things.

SitePoint Premium

HowToDoInJava

Java hashCode() and equals() Methods

Lokesh Gupta

February 23, 2023

Learn about Java hashCode() and equals() methods, their default implementation, and how to correctly override them. Also, we will learn to implement these methods using 3rd party classes HashCodeBuilder and EqualsBuilder .

The hashCode() and equals() methods have been defined in Object class which is parent class for all java classes. For this reason, all java objects inherit a default implementation of these methods.

1. The hashCode() and equals() Methods

  • equals(Object otherObject) – verifies the equality of two objects. It’s default implementation simply checks the object references of two objects to verify their equality. By default, two objects are equal if and only if they refer to the same memory location. Most Java classes override this method to provide their own comparison logic.
  • hashcode() – returns a unique integer value for the object in runtime. By default, Integer value is derived from the memory address of the object in the heap (but it’s not mandatory). The object’s hash code is used for determining the index location when this object needs to be stored in some HashTable like data structure.

1.1. Contract between hashCode() and equals()

Overriding the the hashCode() is generally necessary whenever equals() is overridden to maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes .

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode () must consistently return the same integer , provided no information used in equals comparisons on the object is modified. This integer need not remain consistent between the two executions of the same application or program.
  • If two objects are equal according to the equals() method, then calling the hashCode() on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals() , then calling the hashCode() on each of the both objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

2. Overriding the Default Behavior

Everything works fine until we do not override any of both methods in our classes. But, sometimes, the application needs to change the default behavior of some objects.

Let us understand why we need to override equals and hashcode methods.

2.1. The Default Behavior

Let’s take an example where your application has Employee object. Let us create a minimal possible structure of Employee class:

Above Employee class has some fundamental attributes and their accessor methods. Now consider a simple situation where you need to compare two Employee objects . Both employee objects have the same id .

No prize for guessing. The above method will print “ false .”

But is it correct after knowing that both objects represent the same employee? In a real-time application, this should return true .

2.2. Overriding only equals()

To achieve correct application behavior, we need to override equals() method as below:

Add this method to the Employee class, and EqualsTest will start returning "true" .

So are we done? Not yet. Let’s test the above-modified Employee class again in a different way.

The above example prints two objects in the second print statement.

If both employee objects have been equal, in a Set which stores unique objects, there must be only one instance inside HashSet because both objects refer to the same employee. What is it we are missing??

2.3. Overriding hashCode() is Also Necessary

We are missing the second important method hashCode() . As java docs say, if we override equals() then we must override hashCode() . So let’s add another method in our Employee class.

Once the above method is added in Employee class, the second statement starts printing only a single object in the second statement and thus validating the true equality of e1 and e2 .

3. EqualsBuilder and HashCodeBuilder

Apache commons provide two excellent utility classes HashCodeBuilder and EqualsBuilder for generating hash code and equals methods.

We can use these classes in the following manner.

4. Generating hashCode() and equals() in Eclipse IDE

Most editors provide common source code templates. For example, Eclipse IDE has the option to generate an excellent implementation of hashCode() and equals() .

Right click on Java file -> Source -> Generate hashCode() and equals() …

Generate HashCode and Equals In Eclipse

5. Best Practices to Follow

  • Always use the same fields to generate hashCode() and equals() . As in our case, we have used employee id .
  • The equals() must be consistent (if the objects are not modified, then it must keep returning the same value).
  • Whenever a.equals(b) , then a.hashCode() must be same as b.hashCode() .
  • If we override one method, then we should override the other method as well.

6. Special Attention When Declared in an JPA Entity

If you’re dealing with an ORM, make sure always to use getters and never use the field references in hashCode() and equals() . Because in ORM, occasionally fields are lazy loaded and not available until we call their getter methods.

For example, In our Employee class if we use e1.id == e2.id . It is very much possible that id field is lazy-loaded. So, in this case, id field inside the methods might be zero or null , and thus resulting in incorrect behavior.

But if uses e1.getId() == e2.getId() , we can be sure even if the field is lazy-loaded, calling the field getter will populate the field first.

Happy Learning !!

Further reading:

  • Python Interview Questions and Answers
  • Java Interview Questions and Answers
  • Java Concurrency Interview Questions
  • Vue.js CRUD Application with Spring Boot
  • Designing a Good Custom Key for HashMap
  • Java OOP Interview Questions with Answers

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java object methods, java object equals().

Java Object clone()

  • Java Object toString()

Java Object hashCode()

Java Object getClass()

Java Tutorials

Java String equals()

  • Java String contentEquals()

The equals() method checks whether two objects are equal.

Syntax of Object equals()

The syntax of the equals() method is:

equals() Parameters

The equals() method takes a single parameter.

  • obj - object which is to be compared with the current object

equals() Return Values

  • returns true if two objects are equal
  • returns false if two objects are not equal

Note : In Java, if two reference variables refer to the same object, then the two reference variables are equal to each other.

Example 1: Java Object equals()

In the above examples, we have created objects of the Object class. Here, the equals() method is used to check if objects are equal to each other.

Example 2: Object equals() With String

In the above example, we have used the equals() method to check if two objects obj1 and obj2 are equal.

Here, initially, both the newly created objects are null . Hence, the method returns true . However, when we assigned values to the objects. The method returns false .

It is because the String class overrides the equal() method so that the method compares the element of the object. Since the values of obj1 and obj2 are different, the method returns false .

Note : The Object class is the superclass for all the classes in Java. Hence, every class and arrays can implement the equals() method.

Sorry about that.

Related Library Functions

Java Library

JavaGoal

equals() method in java

In this article, we will discuss the most important topic, which is the equals() method in Java . Everyone knows the equals() method in java is used to compare the objects. But how we can use it? How to override the equals() method in java in user-defined classes. Here is the table content of the article will we will cover this topic.

1. What is the equals() method? 2. Why OR When we should Override the equals() method? 3. Best practices for the Overriding equals() method?

What is the equals() method?

The equals() method is defined in the Object class which is the super most class in Java. This method is used to compare two objects and it returns the boolean value based on the comparison. Let’s have a look at the code.

As you can see in the above code, it compares the given object obj to “this” object. Here “this” is the object on which the method is called.

As you already know every class in java is the child of the Object class . It means each class inherits the equals() method from the Object class . You can override the equals() method as per your functionality. Suppose you want to compare the object’s own equality condition. Then it is recommended to override the equals(Object obj)  method.

NOTE: It is always recommended if you are overriding the equals() then you must override the hashCode() method. We’ll discuss it in detail .

Let’s take the example from the String class. In the String class , the equals() method is overridden and provided the equality condition accordingly.

As you can see in the above code the String class overridden the method and comparing two strings. It compares the two given strings based on the content of the string. It returns the boolean value. If both strings are not the same then it returns false otherwise, it returns true.

Why OR When we should Override the equals() method?

The default implementation of the equals() method compares only the references of objects. But sometimes default implementation is not useful, and we want to compare the objects as per our requirements. In these types of situations, it is better to override the equals() method .

Let’s discuss it with an example. We will create a user-defined class and let’s see what will be the result of comparison when we will override the equals() method in java or not? Let’s take an example of the default implementation in java equals() method.

Output: Is both employee have same id: false false

Reason: You must see emp2 and emp3 have the same name and id. But the equals() method says these do not equal because when we compare emp2 and emp3 , it is checked whether both emp2 and emp3 refer to the same object or not. The compiler made a call to the equals() method of the Object class and it compares the references of the object.

equals() method in java

The emp2 and emp3 refer to two different objects, hence the value (emp2 == emp3) is false. If we create another reference say emp4 like following:

Employee emp4 = emp3; then (emp3 == emp4) will give true.

So, how do we check for the equality of values inside the objects? We can achieve this task by overriding the equals() method of the Object class. We can override the equals() method in our class to check whether two objects have the same data or not.

Output: Is both employee have same id:false true

NOTE: Whenever we override the equals() method , it is recommended to also override the hashCode() method . If you are not overriding the hashCode() method , it can give different hash values in the case of collections. We will discuss this in a separate post.

Best practices for Overriding equals() method

Let’s discuss the best approach to overriding the equals() method in Java.

1.  You must place the null check in the equals() method . If the given object is null , then return false.

2. Before making a comparison further, you must check whether both objects are belonging to the same class or not. You can check this by using of getClass() method . You can use the instanceOf operator also but instanceOf  check returns true for subclass also, so it does not strictly equal comparison.

3. You should try to compare numeric attributes because comparing numeric attributes is fast. But in some cases numeric value is not available then you can compare those attributes which take less time to compare. If the first attribute comparison does not match, then return false. You should not try to match the rest of the attributes.

4. It would be better if you are using  @Override annotation  whenever overriding the method. Reason:  Let’s say the programmer wants to overload the equals() method of the Object class .

 but  unintentionally he/she overloads equals method by writing:

Instead of using  Object  as an argument, they use the class name (Employee). If you use @Override annotation , then the compiler takes care of these things. If the equals() method is not overridden or the programmer made some typo mistake then the compiler will show a compilation error.

The method equals(Employee) of type Employee must override or implement a supertype method.

2 thoughts on “equals() method in java”

It very thorough explanation. thank you

Welcome Nabin 🙂

Leave a Comment Cancel reply

You must be logged in to post a comment.

how to make equals method in java

Java's Object Methods: equals(Object)

how to make equals method in java

  • Introduction

This article is a continuation of a series of articles describing the often forgotten about methods of the Java language's base Object class. The following are the methods of the base Java Object which are present in all Java objects due to the implicit inheritance of Object.

  • equals (you are here)
  • wait & notify

The focus of this article is the equals(Object) method which is used to test for equality among objects and gives the developer the ability to define a meaningful test of logical equivalence.

  • == vs equals(Object)

As you might have guessed the equals(Object) method is used to test for equality among reference types (objects) in Java. Ok, makes sense but, you might also be thinking "Why can't I just use == ?" The answer to this question is that when it comes to reference types the == operator is only true when comparing two references to the same instantiated object in memory. On the other hand the equals(Object) can be overridden to implement the notion of logical equivalence rather than mere instance equivalence .

I think an example would best describe this difference between using the == verse the equals(Object) method on Strings.

In the example above I created and compared three String variables: myName , myName2 which is a copy of the reference to myName , and myName3 which is a totally new instance but with the same content. First I show that the == operator identifies myName and myName2 as being instance equivalent, which I would expect because myName2 is just a copy of the reference. Due to the fact that myName and myName2 are identical instance references it follows that they have to be logically equivalent.

The last two comparisons really demonstrate the difference between using == and equals(Object) . The instance comparison using == demonstrates they are different instances with their own unique memory locations while the logical comparison using equals(Object) shows they contain the exact same content.

  • Diving into equals(Object)

Ok, we now know the difference between == and equals(Object) , but what if I were to tell you the base implementation of the Object class actually produces the same result as the == operator?

What...!? I know... that seems strange, but hey the developers of Java had to start somewhere. Let me say that again, by default the equals(Object) method that you inherit in your custom classes simply tests for instance equality. It is up to us as the developers to determine if this is appropriate or not, that is, to determine if there is a notion of logical equivalence that is required for our class.

Again, let me use the Person class that I introduced previously in this series for more demonstration.

Let me again use a simple program wrapped in a Main class that demonstrates both identical instance equality and logical equality by overriding equals(Object) .

As you can see the two people instances me and me2 are neither logically or instance equivalent out of the box, even though one would reasonably conceive that me and me2 represent the same thing based on the content.

This is where it becomes important to override the default implementation and provide one that makes sense for the class being defined. However, according to the official Java docs there are some rules that need to be followed when doing so to avoid problems with some important implementation dependencies of the language.

The rules outlined in the equals Java docs for given object instances x , y , and z are as follows:

  • reflexive: x.equals(x) must be true for all non-null reference instances of x
  • symmetric: x.equals(y) and y.equals(x) must be true for all non-null reference instances of x and y
  • transitive: if x.equals(y) and y.equals(z) then x.equals(z) must also be true for non-null reference instances of x , y , and z
  • consistency: x.equals(y) must always hold true where no member values used in the implementation of equals have changed in x and y non-null reference instances
  • no null equality: x.equals(null) must never be true
  • always override hashCode() when overriding equals()
  • Unpacking the Rules of Overriding equals(Object)

A. Reflexive: x.equals(x)

To me this is the easiest to grasp. Plus the default implementation of the equals(Object) method guarantees it, but for the sake of completeness I will provide an example implementation below that follows this rule:

B. Symmetric: x.equals(y) and y.equals(x)

This one may seem intuitive at first glance, but it is actually quite easy to make a mistake and violate this rule. In fact, the main reason this is often violated is in cases of inheritance, which happens to be a very popular thing in Java.

Before I give an example let me update the equals(Object) method to account for the most obvious new requirement, which is the fact that the equivalence test must implement a logical test in addition to the instance equality test.

To implement a logical test I will want to compare the state-containing fields between two instances of the people class, described as x and y . In addition I should also check to make sure the two instances are of the same instance type, like so:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Ok, it should be evident that Person now has a much more robust equals(Object) implementation. Now let me give an example of how inheritance can cause a violation of symmetry. Below is a seemingly harmless class, called Employee , that inherits from Person .

Hopefully you are able to notice that these should not be treated as equal instances, but you may be surprised with what I'm about to show you.

Oops! Clearly a violation of symmetry, billy equals billyEmployee but the opposite is not true. So what do I do? Well, I could do something like the following, given that I wrote the code and know what inherits what, then modify the Employee equals(Object) method like so:

Yay I have symmetry! But am I really ok? Notice here how I'm going out of my way to make Employee now conform... this should be sending up a red flag which will come back to bite me later as I demonstrate in the next section.

C. Transitivity: if x.equals(y) and y.equals(z) then x.equals(z)

Thus far I have ensured that my Person and Employee classes have equals(Object) methods that are both reflexive and symmetric, so I need to check that transitivity is also being followed. I'll do so below.

Darn! I was on such a good path there for a while. What happened? Well it turns out in classical inheritance within the Java language you cannot add an identifying class member to a subclass and still expect to be able to override equals(Object) without violating either symmetry or transitivity. The best alternative I have found is to use composition patterns instead of inheritance. This effectively breaks the rigid hierarchy of inheritance between the classes, like so:

D. Consistency: x.equals(y) as long as nothing changes

This one is really very easy to comprehend. Basically, if two objects are equal then they will only remain equal as long as neither of them change. Although this is easy to understand, caution should be taken to ensure that values do not change if there could be negative consequences resulting from such as change.

The best way to ensure things do not change in a class is to make it immutable by only supplying one way to assign values. Generally this one way on assignment should be via a constructor during instantiation. Also declaring class fields final can help with this.

Below is an example of the Person class defined as an immutable class. In this case two objects that are initially equal will always be equal because you cannot change their state once created.

E. No null equality: x.equals(null)

Sometimes you will see this enforced via a direct check for the Object instance o being equal to null , but in the above example this is implicitly checked using the !(o instanceof Person) due to the fact that the instanceof command will always return false if the left operand is null.

F. Always override hashCode() when overriding equals(Object)

Due to the nature of various implementation details in other areas of the Java language, such as the collections framework, it is imperative that if equals(Object) is overridden then hashCode() must be overridden as well. Since the next article of this series is going to specifically cover the details of implementing your own hasCode() method I will not be covering this requirement in any more detail here other than to say that two instances that exhibit equality via the equals(Object) method must produce the identical hash codes via hashCode() .

This article described the meaning and use of the equals(Object) method along with why it may be important for your programs to have a notion of logical equality that differs from identity (instance) equality.

As always, thanks for reading and don't be shy about commenting or critiquing below.

You might also like...

  • Java: Finding Duplicate Elements in a Stream
  • Spring Boot with Redis: HashOperations CRUD Functionality
  • Spring Cloud: Hystrix
  • Java Regular Expressions - How to Validate Emails

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

I am both passionate and inquisitive about all things software. My background is mostly in Python, Java, and JavaScript in the areas of science but, have also worked on large ecommerce and ERP apps.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2024 Stack Abuse. All rights reserved.

Javatpoint Logo

Java Object 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

RSS Feed

  • 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

Character.equals() method in Java with examples

  • Charset equals() method in Java with Examples
  • Date equals() method in Java with Examples
  • AbstractSet equals() Method in Java with Examples
  • Byte equals() method in Java with examples
  • Constructor equals() method in Java with Examples
  • AbstractMap equals() Method in Java with Examples
  • ChoiceFormat equals() method in Java with Examples
  • AbstractList equals() method in Java with Examples
  • DateFormat equals() Method in Java with Examples
  • ChronoPeriod equals() method in Java with Examples
  • ByteBuffer equals() method in Java with Examples
  • Double.equals() Method in Java with Examples
  • DecimalStyle equals() method in Java with Example
  • CharacterIterator clone() method in Java with Examples
  • Boolean equals() method in Java with examples
  • Java File Class equals() Method with Examples
  • CompoundName equals() method in Java with Examples
  • Set equals() method in Java with Examples
  • CompositeName equals() method in Java with Examples

The java.lang.Character.equals() is a function in Java which compares this object against the specified object. If the argument is not null then the result is true and is a Character object that represents the same char value as this object.

Parameters: The function accepts a single parameter obj which specifies the object to be compared with.

Return Value: The function returns a boolean value. It returns true if the objects are same, otherwise, it returns false.

Below programs illustrates the above method:

Reference : https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object)

Please Login to comment...

Similar reads.

  • Java-Character
  • Java-Functions
  • Java-lang package

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Learn Java equals() method with 5 Examples

    how to make equals method in java

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

    how to make equals method in java

  3. Java equals Method

    how to make equals method in java

  4. Java: Creating equals(Object) methods

    how to make equals method in java

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

    how to make equals method in java

  6. How to Use the char equals() Method in Java

    how to make equals method in java

VIDEO

  1. == and equals method

  2. How does equals() method works in Java? #javainterviewquestions

  3. equals( ) vs == in java

  4. Java Interview Questions #21- What is the difference between == and equals()?

  5. Equals Method Comparing Objects in Java || Objects Comparison Using Equals in Java by som sir

  6. Java Practice It

COMMENTS

  1. java

    The String class has overridden the equals() method. Please follow the String equals() documentation.. a.equals(b) has returned true, meaning the condition a==b is satisfied. This is the default implementation of equals() in the Object class, and the String class has overridden the default implementation. It returns true if and only if the argument is not null and is a String object that ...

  2. String equals() Method in Java

    The equals () method of the String class compares the content of two strings. It returns false if any of the characters are not matched. It returns true if all characters are matched in the Strings. It compares the value's character by character, irrespective of whether two strings are stored in the same memory location.

  3. Java String equals() Method

    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.

  4. How to Implement Java's equals Method Correctly

    Many data structures, most notably Java's own collection framework, use equals to check whether they contain an element. For example: List<String> list = Arrays.asList("a", "b", "c"); boolean ...

  5. How To Use .equals Method In Java

    s1 and s2 objects are compared with equals () method as follows: System.out.println("s1 and s2 are equal : "+(s1.equals(s2))); It gives the following output on the console: s1 and s2 are equal : true. This is because the equals () method compares the content of objects s1 and s2.

  6. Java equals() and hashCode() Contracts

    Java SE defines the contract that our implementation of the equals() method must fulfill. In short, most criteria follow common sense but we can define the formal rules that the equals() method must follow. It must be: reflexive: an object must equal itself; symmetric: x.equals(y) must return the same result as y.equals(x)

  7. Java hashCode() and equals() Methods

    Right click on Java file -> Source -> Generate hashCode () and equals () …. Generate hashCode () and equals () In Eclipse. 5. Best Practices to Follow. Always use the same fields to generate hashCode() and equals(). As in our case, we have used employee id.

  8. How to properly implement equals in Java

    1. If you're using eclipse (netbeans has similar features, as do most java IDEs), you can simply got to the "Source" menu, and choose "Generate hashcode () and equals ()". Then you select the fields you want to be considered (in your case the list of enum values. That being said, assuming you already have the enum, here's the code that eclipse ...

  9. Java Object equals()

    The method returns false. It is because the String class overrides the equal() method so that the method compares the element of the object. Since the values of obj1 and obj2 are different, the method returns false. Note: The Object class is the superclass for all the classes in Java. Hence, every class and arrays can implement the equals() method.

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

    We'll start by understanding reference comparison, which is represented by the equality operator ( == ). Reference equality occurs when two references point to the same object in the memory. 2.1. Equality Operator With Primitive Types. We know that the primitive types in Java are simple, non-class raw values.

  11. equals() method in java & Best practices for Overriding

    In this article, we will discuss the most important topic, which is the equals() method in Java. Everyone knows the equals() method in java is used to compare the objects. But how we can use it? How to override the equals() method in java in user-defined classes. Here is the table content of the article will we will cover this topic. 1.

  12. Overriding equals method in Java

    We can override the equals method in our class to check whether two objects have same data or not. Output: As a side note, when we override equals (), it is recommended to also override the hashCode () method. If we don't do so, equal objects may get different hash-values; and hash based collections, including HashMap, HashSet, and Hashtable ...

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

  14. Method Class

    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. Two Methods are the same if they were declared by the same class and have the same name and ...

  15. Java's Object Methods: equals(Object)

    The rules outlined in the equals Java docs for given object instances x, y, and z are as follows: reflexive: x.equals(x) must be true for all non-null reference instances of x. symmetric: x.equals(y) and y.equals(x) must be true for all non-null reference instances of x and y.

  16. Override equals method in Java

    Using the equals () method, we create two objects from the main method by giving identical data and comparing the results. This software returns false because the Object class' equals () method only returns true if the references to the objects are identical. Example code for overriding the equals method: EqualsExpl.java. import java.util.Scanner;

  17. java

    Since primitive types (ints, longs, etc.) don't have any methods on them (including .equals(), you have to compare these fields using == rather than .equals(), as shown in the example above. This isn't the most complete solution (there's plenty of good information answering this question ), and you should also override Object.hashCode() if you ...

  18. Java Object equals() Method with Examples

    Learn how to use the equals() method of Java Object class to compare two objects for equality, with examples and syntax on javatpoint.com.

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

    hashCode () method. It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing based collections like HashMap, HashSet, HashTable….etc. This method must be overridden in every class which overrides equals () method. Syntax : public int hashCode() // This method returns the hash code value.

  20. How to override equals method in Java

    Item 10: Obey the general contract when overriding equals. According to Effective Java, Overriding the equals method seems simple, but there are many ways to get it wrong, and consequences can be dire. The easiest way to avoid problems is not to override the equals method, in which case each instance of the class is equal only to itself. This is the right thing to do if any of the following ...

  21. Character.equals() method in Java with examples

    The java.lang.Character.equals() is a function in Java which compares this object against the specified object. If the argument is not null then the result is true and is a Character object that represents the same char value as this object.

  22. java

    I need to adapt a Mockito verify method to check if the first parameter is equal to the expected value, and the second parameter, being a complex object, may have some fields set to null. I want to verify only the fields that are not null, that have a value.