Make Selenium Easy

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

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.

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.

Table of Contents

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

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

by Amod Mahajan time to read: 1 min
%d bloggers like this: