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.
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
The two main reasons why strings are immutable in many modern languages, including Java, are security and performance (or, more precisely, chance for optimizations).
The fact that strings are final
is to ensure their immutability (by forbidding anyone from extending them and making them mutable again).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With