Why are strings immutable in Java?

Strings in Java are immutable; an immutable class is a class whose object cannot be modified. The value of the immutable class object is initialized at the time of creation. Below are a few advantages of an immutable class:

1. String Pool Requirement

String pool is a specific storage area for string objects. If a string object is created and that string already exists, then, instead of creating a new object on the heap, the reference of the same object is returned. If string is mutable, then changing one reference will change the value for all the string objects.

svg viewer

2. Caching KEY

Since a string object is immutable, its hashcode is cached at the time of creation so that it can be used multiple times without calculation. This immutability feature makes it an appropriate choice for a candidate key for HashMaps.

3. Security

Strings are widely used as parameters in network connections, file-openings, etc. If a string is mutable, then a connection or file would be changed which would lead​ to a serious security threat.

svg viewer

4. Thread-safe

These immutable string objects are thread-safe as well. Since these objects cannot be changed or modified, they can be shared between threads which eliminates the need for synchronization.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved