Forums Register Login
Why do we have an equals method in String Class
I wanted to know why we have an equals method in String class when that method is already there in the Object class? Can anyone explain?
maybe because the Object class is on the top of the hierarchy and all of the other classes inherit from it directly or indirectly. consider this:

public class Test {
//some testing code goes here...

this class also inherits from the Object class even am not specifying this here like "... Test extends Object {"
so this way my class inherited also the equals() method from Object class and so others do. The reason you can find equals() method in String class (and others) is that the String class is overriding its behavior to fit its needs.

Originally posted by Anil Verghese:
I wanted to know why we have an equals method in String class when that method is already there in the Object class? Can anyone explain?

The equals() method written in Object class is too generic and doesn't serve the purpose of String equality. Hope you might have got a chance to look at the source code in equals() in Object and String classes.

The equals() method in Object class simply checks if the references of the objects are same (using == double equals) check.

Run this code you will notice the difference


You mean to say that there is a difference between them , could you tell me what this difference is?
The equals method in the Object class is a default implementation, it checks whether two objects are in fact the same object.
This is often not a very usable implementation and therefore a lot of classes will implement their own version of the method. For example for String, its own version of the method will check whether both objects contain the same character sequence, the behaviour you would expect for a String class.
This gives a nice explanation of the difference.
The equals class is overridden in String so that two String objects can be tested for equality.

Consider how you would test if two objects are equal. For example our Quad below:

How does Java know that a Quad is only equal to another Quad only if its height AND width are equal?
You cant use the == operator, as in the case of objects this only checks for the equality of references.

The only way is to tell Java how one Quad object would equal another, and the way to do this is, with teh equals method.

It is worth noting that you need to override both equals and hashCode to make use of some collections.

Hope this helps, oh and excuse the naff code.

If you are using a wood chipper, you are doing it wrong. Even on this tiny ad:
Become a Java guru with IntelliJ IDEA

This thread has been viewed 1125 times.

All times above are in ranch (not your local) time.
The current ranch time is
Mar 20, 2019 05:07:13.