Why String is immutable or final in Java [duplicate]

我是研究僧i 提交于 2019-12-03 07:14:02

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!