Why String is immutable or final in Java

This is one of the most popular String Interview questions in Java, which starts with discussion of, What is String, How String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . Though there could be many possible answer for this question, and only designer of String class can answer this , I think below two does make sense

1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"


Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java". Also to be immutable you have to be final, so that your subclass doesn't break immutability. what do you guys think ?


Few more String related post from Javarevisited, you may like:


Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz2ki2LJpiX
### C++ 编程中的编码标准与最佳实践 #### 成员变量命名约定 在 C++ 中,成员变量的命名通常遵循特定的前缀规则以提高可读性和一致性。例如,在 Qt 和微软风格中,推荐使用 `m_` 前缀来表示类的成员变量[^1]。这种做法的优点在于它能够清晰地区分局部变量、全局变量以及成员变量,从而减少混淆并增强代码的可维护性。 然而需要注意的是,尽管该方法被广泛采用,但在极少数场景下可能会引发命名冲突问题。不过总体而言,这类情况较为少见,因此其依然是许多项目组首选的方式之一。 #### 函数与参数名称的选择 对于函数名及其参数的名字选取上,应力求做到直观易懂。具体来说就是让名字能准确反映其所执行的操作或者所代表的数据含义。比如当定义一个用于计算矩形面积的方法时可以命名为 `calculateArea()` 而不是简单地叫作 `calc()`. 同样地, 参数也应当具有描述性的标签以便于理解它们的作用. 另外还需要注意大小写规则的一致应用; 大多数时候我们会看到 PascalCase(首字母大写的单词组合形式)应用于类型(class 或 struct),而 camelCase (除了第一个词外其余各部分首个字符均转成大写字母的形式)则更多见诸于方法(methods)/functions 及 variables 上面 [^2]. #### 注释的重要性 良好的注释可以帮助其他开发者快速了解复杂逻辑背后的意图。建议为每一个公共接口提供详尽说明文档的同时也要记得内部实现细节处适当加些解释文字。尤其是那些不那么显而易见的部分更是如此 - 即使现在看来再明白无误的东西随着时间推移也可能变得难以捉摸起来! 此外还有一种叫做 Doxygen 的工具特别适合用来生成基于源文件内的特殊标记自动生成API手册等功能强大又方便实用的好东西值得尝试一下哦! ```cpp /// @brief Calculates the area of a rectangle. /// @param width The width value as double precision floating point number. /// @param height The height value also given by user which is again typecasted into float automatically here inside this function body itself before returning final result back out there whereever needed most probably later stages during runtime execution phase maybe? Who knows exactly though right now anyway... :P double calculateRectangleArea(double width , double height){ return static_cast<double>(width * height); } ``` #### 避免魔法数字 所谓"魔法数",指的是直接嵌入到程序里的常量数值却没有赋予任何意义或上下文关联的信息. 这样的做法不仅会让后续阅读者感到困惑而且一旦将来需要修改这些值的时候也会非常麻烦甚至可能导致错误发生几率增加不少倍呢! 所以最好是把这些重要的固定数据项单独提取出来并通过枚举(enum)或者是宏(define)等形式加以声明管理起来会更好一些啦~ ```cpp #define MAX_CONNECTIONS 100 // Maximum allowed connections at once time period per server instance running currently active session only please thank you very much indeed sir/ma'am! enum StatusCodes { OK=200, NOT_FOUND=404 }; // HTTP status codes represented via enumeration types instead raw integer literals directly everywhere throughout entire application codebase structure hierarchy levels layers stacks queues whatever yeah sure why not go ahead try me I dare ya ;) ``` #### 使用const关键字保护不变量 如果某个对象在其生命周期内不应该改变状态的话就一定要毫不犹豫地将其设置成为只读属性(const). 这不仅可以防止意外更改还可以帮助编译器优化性能表现等方面带来积极正面影响效果显著可见一斑啊朋友们听到了吗?! ```cpp void displayMessage(const std::string& messageText){ /* ... */ } // Prevent modification attempts against original string passed along argument list while calling current method invocation sequence order pattern matching algorithm implementation details etcetera ad infinitum et cetera... class ImmutableClass { private: const int fixedValue; public: explicit ImmutableClass(int initialValue):fixedValue(initialValue){} }; ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值