Last Updated:

Why are strings in Java immutable?

String is one of the most commonly used classes in any programming language. As we know, a string in Java is immutable and finalized, and the Java Runtime supports a common string pool, which makes it a special class.

Java immutable

Benefits of String Immutability in Java

  1. The very existence of a string pool is possible only because a string in Java is immutable. Therefore, the Java Runtime saves a lot of space in the general heap (java heap space). The fact is that different variables can access the same String variable in the pool. If the string were not immutable, then internment of such a string would not be possible. That's because any variable could change the value of this string and this would be immediately reflected in other variables.
  2. If the string is not immutable, then this causes a serious threat to the security of your program. For example, to connect to a database, the database user name and password are passed as strings. It's the same in socket programming, where the host and port are passed as regular Strings. That is why the string value cannot be changed. Otherwise, any hacker or malware can change the meaning of strings and cause security problems in your program.
  3. Strings are immutable, which means they are thread-safe. This saves us from using synchronizations while working in a multi-threaded environment.
  4. Strings are also used in the Java classloader, and string immutability makes it safe to load the class. For example, you try to load the java.sql.Connection class, but the link value has been changed by malware. This can lead to unexpected results and data in your database.
  5. Strings are immutable, which means that their hash codes are cached at the time of creation and do not need another calculation. This makes strings a great candidate for use as a key in Map and will run faster than HashMap objects.

That's all the arguments in favor of the immutability of strings in Java.