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:-

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

Code is as below:-

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:-

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.

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply