Why string is immutable in java is one of the frequently asked interview questions.In the last video, we have covered why string is immutable in string pool point of view.In case you have missed that out you can watch this at the below link
Like string class, String class hashcode() is also special.String class hashcode method compute hashcode only one time and then cached in the string object header forever.In this video, we are going to see this in detail.
Well now a most important question, how is this hashcode caching of string helping us? Well, string is immutable in java, this confirms that the content of the object will not change.If so then there is no meaning of calculating the string hashcode again and again as JVM internally uses string characters to calculate the hashcode. So if the string content is not going to change as it’s immutable, then the hashcode is not going to change.
In this way String caching help us to perform a faster operation with a hash-based collection like hashmap, HashSet where there is need of calculating the hashcode again and again.So string used popularly as a key in the hashmap.
So a Note here: The hashcode method of string class in java run for only one time, calculate the hashcode then cached it in the string object header.
So when it comes to "string in java interview questions”, This topic has so much weight.So let’s explore more with this tutorial and the get the answers to the below questions :
1)What is string hashcode caching?
2)Why is String used as a key in hashmap?
3)What is the benefits string hashcode caching and how they help them hash-based collections.
4)And the most important question, Why string is immutable in java?
In case you might be wanted to know how the hashmap works internally, I have already videos available for this which will beneficial to understand this tutorial.Find it at the below link :
subscribe to my channel by clicking on the link below.
Stay tuned and like my Facebook page for more.
credits : -
Adventures by A Himitsu https://soundcloud.com/a-himitsu
Creative Commons — Attribution 3.0 Unported— CC BY 3.0
Music released by Argofox https://youtu.be/8BXNwnxaVQE
Music provided by Audio Library https://youtu.be/MkNeIUgNPQ8
intro template :
Why string is immutable in java is one of the frequently asked interview questions. We have covered why string is immutable in string pool point of view. String class hashcode() is also special.String class hashcode method compute hashcode only one time and then cached in the string object header forever.