This is an old yet still popular question. There are multiple reasons that String is designed to be immutable in Java. A good answer depends on good understanding of memory, synchronization, data structures, etc. In the following, I will summarize some answers.

1. Requirement of String Pool

  String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

  The following code will create only one string object in the heap.

String string1 = "abcd";
String string2 = "abcd";

  Here is how it looks:

  If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. Allow String to Cache its Hashcode

  The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.

In String class, it has the following code:

private int hash;//this is used to cache hash code.

3. Security

  String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Here is a code example:

boolean connect(string s){
if (!isSecure(s)) {
throw new SecurityException();
}
//here will cause problem, if s is changed before this by using other references.
causeProblem(s);
}

In summary, the reasons include design, efficiency, and security.

Why string is immutable in Java ?的更多相关文章

  1. 为什么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 ...

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

  3. Why String is Immutable or Final in Java

    The string is Immutable in Java because String objects are cached in String pool. Since cached Strin ...

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

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

  5. JAVA 中为什么String 是immutable的

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

  6. 为什么 String 是 immutable 类

    二哥,你能给我说说为什么 String 是 immutable 类(不可变对象)吗?我想研究它,想知道为什么它就不可变了,这种强烈的愿望就像想研究浩瀚的星空一样.但无奈自身功力有限,始终觉得雾里看花终 ...

  7. 前台传参数时间类型不匹配:type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'

    springMVC action接收参数: org.springframework.validation.BindException: org.springframework.validation.B ...

  8. Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx': no matching editors or conversion strategy found

    今天在完成项目的时候遇到了下面的异常信息: 04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.cor ...

  9. spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endtime'

    在使用spring mvc中,绑定页面传递时间字符串数据给Date类型是出错: Failed to convert property value of type [java.lang.String] ...

随机推荐

  1. 慕课网-安卓工程师初养成-1-5 使用Eclipse开发Java程序

    来源: http://www.imooc.com/video/1412 eclipse --- IDE 集成开发环境(IDE)是一类软件 将程序开发环境和程序调试环境集合在一起,提高开发效率 其他ID ...

  2. 第4章 awk编程

    1 awk编程模型       2 awk用法 调用awk有三种方法(与sed类似): 在Shell命令行输入命令调用awk,格式为: awk [-F 域分隔符] 'awk程序段' 输入文件 将awk ...

  3. 查看Eclipse版本号的方法

    查看Eclipse版本号的方法如下所示: 1:假设Eclipse已打开Eclipse的菜单栏: Help-->About Eclipse弹出框中会显示一排logo,点击eclipse的那个log ...

  4. Acronis Server备份Linux系统

    Acronis Server备份Linux系统 前段时间用Acronis Disk Director Suite解决了Thinkpad笔记本在win7的分区问题(http://chenguang.bl ...

  5. openstack4j接口调试

    //import java.util.List;////import org.openstack4j.api.OSClient.OSClientV3;//import org.openstack4j. ...

  6. http://www.cnblogs.com/vowei/archive/2012/08/24/2654287.html

    原创开源项目 - 扩展iQuery - 知平软件 - 博客园 return node.getProperty("mBottom").getValue();

  7. EasyUI学习笔记

    1,tabs获得被选中的标题 var tabTitle = $('#tabs').tabs('getSelected').panel('options').title;//获得被选中的标题 2.当设置 ...

  8. console.log在线调试

    前端开发人员工作有时候会用到console.log,PC端直接能打开开发者工具.但是移动端就不太方便了,为此提供一种简单的方法,只需2步: 1.打开http://jsconsole.com/  输入: ...

  9. maven auto-config 多环境自动打包

    摘自:http://doc.okbase.net/bjhecwq/archive/118121.html maven有许多优秀的插件,最近在研究打包中替换多重环境的配置,同事介绍使用阿里的auto-c ...

  10. JS兼容getElementsByClassName

    getElementsByClassName是通过class来获取DOM,但是IE8及以下不能兼容.这里做了一下兼容性. HTML: <div class="pox"> ...