Why String is immutable or final in Java

final, immutability, java, string

Solution

It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable

Immutability of `String` solves some synchronization issues, it makes the `String` thread safe

To support StringPool facility

To cache the `hashcode` of `String`

To support class loading mechanism in which `String` is used as arguments. String being mutable results in wrong class being loaded

Problem

As i was told this is important String Interview question in Java, which starts with discussion of " What is String ", how String is different in java than in C or C++ and then you are asked about immutable objects and you're asked the main question: " Why String is immutable or final in Java ". Can you share your Ideas ? Thanks in advance.

Original source

Related problems