0

In String class hashCode() method is readable format of memory address.

As per the below code == operator compares memory location or hashcodes.

then how == operator returning false and hashCode() method returns true.

public class TestStringEquals {
    public static void main(String[] args) {
         String s1="Hello World";
         System.out.println(s1.toUpperCase()==s1.toUpperCase());   //false
         System.out.println(s1.toUpperCase().hashCode()==s1.toUpperCase().hashCode());   //true
    }
}
  • "== operator compares memory location or hashcodes" nope, hashcodes have nothing to do with memory location. – Federico klez Culloca Dec 23 '20 at 08:53
  • Two objects that have the same hash code don't necessarily have to be equal, even less so do they necessarily have to be the same instance. Besides, `String` overrides `hashCode` to return a hash based on its contents; so even if `Object#hashCode` is related to memory location that's irrelevant to `String`. – Slaw Dec 23 '20 at 08:53
  • @Slaw, thanks for immediate reply, so == operator doesn't compare hashCodes? – Murali krishna Konduru Dec 23 '20 at 08:59
  • No. `==` checks for reference equality (i.e. are the two objects the same _instance_). Note that `==` does not translate to `equals` (though the _default implementation_ of `Object#equals` is the same as `==`). – Slaw Dec 23 '20 at 09:02
  • Two unequal objects can have the same hashcode. Try out the hashcode of strings `AA` and `Ab` – Thiyagu Dec 23 '20 at 09:03

1 Answers1

1

== compares the starting pointer of two objects in Memory. hascode is like checksum.

quietor
  • 71
  • 4
  • for the answer, it is more clear in this link.http://www.cs.umd.edu/~meesh/420/ProjectBook/part1/p11/node39.html#:~:text=Note%20that%20in%20Java%2C%20the,that%20implements%20Comparable%20is%20String. – Murali krishna Konduru Dec 23 '20 at 11:03