0

I was reading about comparison of String Objects in java using == operator.

class Teststringcomparison3{  
 public static void main(String args[]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3=new String("Sachin");  
   System.out.println(s1==s2);//true (because both refer to same instance)  
   System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
 }  
}  

It says The == operator compares references not values.
But when I tried printing the reference for all three strings it turned out to be same.

public class StringComparison {

    public static void main(String args[]){

        String s1="Sachin";
        String s2="Sachin";
        String s3=new String("Sachin");

        System.out.println(Integer.toHexString(s1.hashCode()));
        System.out.println(Integer.toHexString(s2.hashCode()));
        System.out.println(Integer.toHexString(s3.hashCode()));
    }
}

enter image description here

Can someone explain what is going on here. Thank you

  • 2
    You are not printing the "reference" and certainly not the "address" of the object but rather the String's hashCode, a calculated value that will be the same for two Strings that are equal (where the `.equals(...)` method returns true). – Hovercraft Full Of Eels May 22 '22 at 12:02
  • 1
    Can you try [`System.identityHashCode(object)`](https://stackoverflow.com/questions/580984/how-do-you-get-the-object-reference-of-an-object-in-java-when-tostring-and-h) instead? – Jeppe May 22 '22 at 12:02
  • @Jeppe yes, its working with identityHashCode. Thanks – Radhika Tiwari May 22 '22 at 12:04
  • 1
    Note: Hashcode is expressed via `int` and since `int` size is 32 bits we can only have 2^32 unique hash codes. Possible amount of unique String objects (texts) is much higher so it is impossible to assign to each unique String unique hashcode. This means that two *non-equal* String objects will at some point have same hashcode. Example `"Aa".hashCode()` == `"BB".hashCode()` == `2112` – Pshemo May 22 '22 at 12:51
  • 1
    Hashcode is useful when we want to organize elements into *group*. For instance some collection can can split its elements into 2 groups based on elements hashcode: odd and even. Now if someone wants to check if `collection.contains(someElement)` then collection can check if hashcode of element is odd or even to know which group it should search/iterate. This means **it can skip searching through elements in other groups**. Now imagine collection split its elements in 4 (or more) groups. This allows it to search only one group and skip searching/iterating other 3. – Pshemo May 22 '22 at 13:01

0 Answers0