+3

Equals()

I can't understand the equals() method in java. Help me.

3/16/2019 6:38:16 AM

Jonny Walker

5 Answers

New Answer

+10

The equals method is defined in the Object class, the mother of all classes which every class implicitly extends. The implementation in the object class is quite simple and often not what you want. It returns true if you call the method from an object and pass in the identical object as an argument. The same what == comparison would result. This is why the equals method often needs to be overridden to compare the classes field values instead of just the object reference. String overrides equals() to deeply compare two Strings, meaning the content of the underlying char array. Note that you must override hashCode if you override equals. More on the topic: https://www.baeldung.com/java-equals-hashcode-contracts

+6

This might help to visualise the diffrenece. String x = "hello"; String y = new String("hello"); //i have to create a new string object of hello here beacuse if i didnt x and y would both be pointing to the same "hello" in string pool meaning that there refrences would be the same if compared. System.out.println("Are both values the same? "+x.equals(y)); System.out.print("Are both refs the same? "+(x==y));

+5

The equals method compares the value of two variables, and returns true if they are equal, and false if they’re not.

+3

Thanx for the help

+2

When a class implements the interface Comparable, it overrides the method equals. Since you can call the method equals on objects of that class, to know whether they are equals or not