Hello guys, after looking into some intense topics, it is time to pick some simple ones. So, in this blog, we are going to talk about String class and String Pool. Let us begin…

String class is one of the widely used classes all around the globe. It is used right from storing a simple string such as name to the encrypted passwords.

If you see the String class definition, it has been declared as final. So once the String object is created, it cannot be modified. Have you ever thought about why it is immutable?. Let us find the answers…

Let us take any login system where you enter your username and password. If String had been mutable, then anyone would have changed the content of the String object and your account would have been compromised.

The String object is one of the widely used candidates for HashMap keys. Since String is immutable, its hashcode is cached at the time of creation and doesn’t need to be calculated again. This makes the String object a great candidate for the key in the Map.

String immutability also helps in saving a lot of heap space as String literals are cached in the String Pool. So, whenever JVM encounters a new string literal, it first checks whether it is present in the String Pool. If it is present, it returns that object reference otherwise it creates a new one in the String Pool, and then the reference of that object is returned.

Some of them might be having a doubt why the following statements are allowed if String is immutable.

#string #string-pool #java #immutable

The Immutable Strings and the String Pool
1.55 GEEK