Search code examples
javastringstring-literals

String hashCodes


Small question.

String s1 = "test";
String s2 = "test";

s1,s2 both have same hashCode value

String sn1 = new String("java");
String sn2 = new String("java");

all of them said sn1 and sn2 have different hashCode values and those are different objects

When I am printing hashCode values it gives same value that means sn1 and sn2 points to the same object or not ?


Solution

  • It is often useful to look at the java code to see what is happening.

    For example the String#hashCode method

    public int hashCode() {
        int h = hash;
        if (h == 0) {
            int off = offset;
            char val[] = value;
            int len = count;
    
                for (int i = 0; i < len; i++) {
                    h = 31*h + val[off++];
                }
                hash = h;
            }
            return h;
        }
    

    As you can see the result is based upon the value of the String, not its memory location.