1

I have a question about address of object in JAVA.

the following is my code.

public class StringCompare {

    public static void main(String[] args) {
        String s1 = "apple";
        String s2 = "apple";
        String s3 = new String("apple");

        boolean b1 = (s1 == s2);
        boolean b2 = (s1 == s3);
        boolean b3 = s1.equals(s2);

        System.out.println(b1); // true
        System.out.println(b2); // false
        System.out.println(b3); // true

        System.out.println("");

        System.out.println("Address of s1 = " + Integer.toHexString(s1.hashCode()));    // 58b835a 
        System.out.println("Address of s2 = " + Integer.toHexString(s2.hashCode()));    // 58b835a
        System.out.println("Address of s3 = " + Integer.toHexString(s3.hashCode()));    // 58b835a
    }
}

I think address of object(s1 and s2) is same.
I think Address of object(s3) is not equal to s1, s2.

but.. result is address of object(s1, s2, s3) is same.

enter image description here

I don't know why s1, s2, s3 address is same..

Please give me some advice.
Thanks.

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Westporch
  • 717
  • 1
  • 7
  • 13
  • 4
    `hashcode()` is **not** the address of an object. – Code-Apprentice Oct 26 '14 at 06:18
  • possible duplicate of [How do hashCode() and identityHashCode() work at the back end?](http://stackoverflow.com/questions/4930781/how-do-hashcode-and-identityhashcode-work-at-the-back-end) – Joe Oct 26 '14 at 06:31

3 Answers3

2

According to the documentation for Object.hashCode():

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Since String overrides equals(), it also overrides hashCode() in order to fulfill this contract. This means that two distinct object which are equals() will still have the same hashcode. Note that this means that the hashcode is not the address of the object. (Although, the default implementation in Object.hashCode() returns a unique identifier of the object itself, which is somewhat similar to its address. Note that this satisfies the equals() contract because the default implementation returns true only when comparing two references to the same object.)

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

You can't get the address of a String. The hashCode() of Object returns something like an address, but String overrides hashCode(). Finally, you can test for reference equality with == but (as you seem to know), you use .equals() for equality testing.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

.hashcode() does not return an address, it returns a hash value which every class in Java implicitly provides. For more info you can read here

kolonel
  • 1,412
  • 2
  • 16
  • 33