What, besides not being inherited from the final class, namely String.class , and the fact that when using the concat() method and the + operation a new object of the String type is created and not existing, is used to determine the immutability of the String class?

As immutable, the String class helps a programmer in real situations. The examples related to HashMap and multithreading would be interesting.

    1 answer 1

    Here the person has already answered your question:

    Security and String pool are the main reasons for String's immutability in Java.

    The security of an object of an immutable String class is determined by the following facts:

    • you can pass a string between threads and not worry that it will be changed
    • no problems with synchronization (no need to synchronize operations with String)
    • no memory leaks
    • Java strings are used to pass parameters for authorization, opening files, etc. - immutability allows to avoid problems with access
    • ability to cache hash code

    String pool allows you to save memory and not create new objects for each duplicate line. In the case of variable lines, changing one line would change all lines of the same content.

    And if you want to change, there is a StringBuffer.

    • As far as I remember a similar explanation, only for all such classes can be found in Effective Java Bloch - abbath0767