Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
strings
immutable

Why are strings immutable in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

java
strings
immutable
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring