Why String is immutable or final in Java [duplicat

2019-03-20 14:32发布

This question already has an answer here:

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.

3条回答
趁早两清
2楼-- · 2019-03-20 14:57

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).

查看更多
Animai°情兽
3楼-- · 2019-03-20 14:57

The most important reason is security.

A lot of security risks would appear if a malicious thread could gain a reference to a mutable String, which is about to be passed into a method that has to validate the String before it performs an important operation. It would be possible for the thread to change the string after it was validated, and then the operation would be carried out using a dangerous String.

Another reason of Why String is immutable in Java is to allow String to cache its hashcode

As mentioned above - the most important reason - security & thread safety.

Consider a scenario, in a banking application for money transfer - the beneficiary account number is defined in a string as "0789567345". If by mistake/intentionally this acc. number is changed, money will go to a wrong account.

Another scenario - if someone change the class name anywhere between processing as ..

getClass().getName().subString(0, 5);

The Class loader will simply say 'Class Not Found

查看更多
\"骚年 ilove
4楼-- · 2019-03-20 15:03

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

查看更多
登录 后发表回答