The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors. Another reason of why String class is immutable could die due to HashMap.

Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in the principle of hashing, which requires same has value to function properly. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.

 

Important and popularity of String as data type, transfer object and mediator has also made it popular in Java interviews. Why String is immutable in Java is one of the most frequently asked 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 them and which scenarios should you use them. This question sometimes also asked, "Why String is final in Java".

On a similar note, if you are preparing for Java interviews, I would suggest you take a loot at the Java Programming interview exposed book, an excellent resource for senior and mid-level Java programmer. It contains questions from all important Java topic including multi-threading, collection, GC, JVM internals and framework like Spring and Hibernate, as shown below:

 

Why String is Final in Java

As I said, there could be many possible answers to this question, and the only designer of String class can answer it with confidence. I was expecting some clue in Joshua Bloch's Effective Java book, but he also didn't mention it. I think following two reasons make a lot of sense on why String class is made Immutable or final in Java:

 
1) Imagine String pool 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. Here is a nice diagram which shows how String literals are created in heap memory and String literal pool.

字节码不可更改
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 a string for opening database connection, you can open any file in Java by passing the name of the file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat, I mean someone can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access to that file. Because of immutability, you don't need to worry about that kind of threats. This reason also gels 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 share 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 the memory leak caused by SubString, which is not a thread related issues but something to be aware of.

String对象的不可变性使得可以缓存这个实例的哈希码
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 invocations.

字节码加载的安全性
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?

Read more

Why String is Immutable or Final in Java的更多相关文章

  1. String的不变性到final在java中用法

    final在Java语言里面啥意思 final修饰一个类,那么这个类就是不可继承.string就是一个非常有名的被final修饰的类,不过他的更加有名的是“不可被修改”. 究竟什么是不可改变?stri ...

  2. JAVA —— String is immutable. What exactly is the meaning? [duplicate]

    question: I wrote the following code on immutable Strings. public class ImmutableStrings { public st ...

  3. java问题解读,String类为什么是final的

    一.理解final 望文生义,final意为“最终的,最后的”,我理解为“不能被改变的”,它可以修饰类.变量和方法. 所以我是否可以理解为被它所修饰的类.变量和方法都不能被改变呢?答案是”是“,因为有 ...

  4. 为什么Java中的String是设计成不可变的?(Why String is immutable in java)

    There are many reasons due to the string class has been made immutable in Java. These reasons in vie ...

  5. Why string is immutable in Java ?

    This is an old yet still popular question. There are multiple reasons that String is designed to be ...

  6. Why String is immutable in Java ?--reference

    String is an immutable class in Java. An immutable class is simply a class whose instances cannot be ...

  7. java的String类型为什么是final

    (转自:http://www.cnblogs.com/ikuman/archive/2013/08/27/3284410.html) 最佳答案: 主要是为了“效率” 和 “安全性” 的缘故.若 Str ...

  8. JAVA 中为什么String 是immutable的

    本文翻译自:http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/ 这是一个很老但很流行的问题,这里有几个原因Stri ...

  9. Java问题解读系列之String相关---String类为什么是final的?

    今天看到一篇名为<Java开发岗位面试题归类汇总>的博客,戳进去看了一下题目,觉得有必要夯实一下基本功了,所以打算边学边以博客的形式归纳总结,每天一道题, 并将该计划称为java问题解读系 ...

随机推荐

  1. 判断资源贴图是否有alpha

    /* modfly selected textures`s maxSize and ImportFormat bool hasAlpha = true; if(hasAlpha)then(textur ...

  2. AliRedis单机180w QPS, 8台服务器构建1000w QPS Cache集群

    转自:http://www.open-open.com/lib/view/open1389880948758.html 引言:        如今redis凭借其高性能的优势, 以及丰富的数据结构作为 ...

  3. repr方法字符串输出实例对象的值

    #coding=utf-8 #repr方法字符串输出实例对象的值 class CountFromBy(object): def __init__(self, val=0, incr=1): self. ...

  4. React Native(十三)——ios键盘挡住textInput

    渐入佳境 用React Native重构的项目也快接近尾声,剩下的就是适配ios的功能了.慢慢地也从中琢磨出了一点门道,于是就遇见了键盘遮挡textInput问题斑斑: 正常页面: android点击 ...

  5. thinkphp3.2 实现留言功能

    写一个例子说明一下: 前端:http://www.mmkb.com/zhendao/index/feedback.html <form method="post" actio ...

  6. 【转载】Yui.Compressor高性能ASP.NET开发:自动压缩CSS、JS

    在开发中编写的js.css发布的时候,往往需要进行压缩,以减少文件大小,减轻服务器的负担.这就得每次发版本的时候,对js.js进行压缩,然后再发布.有没有什么办法,让代码到了服务器上边,它自己进行压缩 ...

  7. python中级---->pymongo存储json数据

    这里面我们介绍一下python中操作mangodb的第三方库pymongo的使用,以及简单的使用requests库作爬虫.人情冷暖正如花开花谢,不如将这种现象,想成一种必然的季节. pymongo的安 ...

  8. css方法 - 移动端reset汇总与注释

    1.解决移动端触摸a元素,会有蓝色阴影 正常状态: 点击时状态: a{ outline:none; -webkit-tap-highlight-color: rgba(,,,); } -webkit- ...

  9. JUnit —— TestSuite 的使用

    首先说一下,suite ,中文是 一套,一组 的意思. 那么,TestSuite,顾名思义,就是用来运行一组测试的. 如何使用呢 ? 假设有个这样的测试类 StudentDAOTest ,代码如下: ...

  10. stopImmediatePropagation和stopPropagation (事件、防止侦听)

    参考: ActionScript 3.0 Step By Step系列(六):学对象事件模型,从点击按扭开始 actionscript宝典 一.事件模型 egret中的事件模型和flash是一样的,但 ...