Java Interview Question 4 – What is HashCode of an Empty String?

As a part of Java Interview Questions, in this post, we will see an interview question which I faced in an interview, “What is HashCode of an Empty String?“.

HashCode is an integer representation which is typically generated by converting the internal address of an object to integer. Object class contains a native method called hashCode() which does the same. But as a programmer, we should override hashCode() and equals() method as required.

String class also overrides hashCode() method and it calculates hashcode of a string using below formula:-

 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 

where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.

Code is as below:-

public int hashCode() {
        // 'hash' is a class level private int and 'value' is a char[] to get all characters of string.
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

Above was basic introduction about hashcode and implementation of hashcode in String class. Now interviewer had asked me “What is HashCode of an Empty String?“.

Hope you can answer this now. HashCode of empty string will be zero. In above code, 'hash' is a class level private int and 'value' is a char[] to get all characters of string. If a string does not contain any characters or string is empty, it will return 'h' as default value of integer which is Zero.

Example Java Code:-

package Concepts;

public class HashCodeInJava {
	
	public static void main(String[] args) {
		
		String str1 = "";
		String str2 = new String();
		
		
		System.out.println(str1.hashCode());
		System.out.println(str2.hashCode());
	}

}

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

Leave a Reply

Your email address will not be published. Required fields are marked *