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. FusionCharts for Flex报错

    1.昨天,我新建了一个Flex项目,并将FusionCharts组件添加进去了,但是Flex应用程序还是报错 具体错误如下: 2.但是,Flex项目已经导入FusionCharts.swc

  2. JS ​ ZERO WIDTH SPACE

    如上编码 ZERO WIDTH SPACE  在各个语言的表达. JS中使用 var b = a.replace(/\u200B/g,''); 来替换,去掉 ZERO WIDTH SPACE . ht ...

  3. flask页面操作gpn接口

    https://wizardforcel.gitbooks.io/flask-extension-docs/content http://cabeza.cn/blog/2016/02/28/datat ...

  4. form 表单默认的提示

    <form method="get" action="" class="form">        <input type ...

  5. Linux之磁盘管理

    本章重点提示: 1):理解基础命令,df,fdisk. 2):磁盘分区的理论基础. 1:查看当前系统分区与挂载情况: [root@localhost ~]# df Filesystem 1K-bloc ...

  6. Unieap3.5-禁用Form表单中的全部标签

    var form=unieap.byId('customerForm'); var children=form.getDescendants(); dojo.forEach(children,func ...

  7. PHP版实现友好的时间显示方式(例如:2小时前)

    完整php类,通常我会配合smary使用,快捷使用 (plugins/function.rdate.php),更多php技术开发就去php教程网,http://php.662p.com <?PH ...

  8. 【风马一族_mysql】MySQL免安装版环境配置图文教程

    mysql存放在某一个磁盘中(笔者使用E盘) 配置系统变量 打开 电脑的属性 点击 高级系统设置 选择 高级 点击 环境变量 选择 系统变量 点击 变量Path,追加 值 E:\mysql-5.6.2 ...

  9. JSP ajax跨域问题 怎么处理 原因:CORS 头缺少 'Access-Control-Allow-Origin')。 ajax http 415

    /** * Project Name:cm2mManage * File Name:CrossSiteFilter.java * Package Name:com.yoxnet.serverframe ...

  10. HTML中Meta属性http-equiv="X-UA-Compatible"详解

    HTML下head中的http-equiv="X-UA-Compatible"详解: X-UA-Compatible是针对IE8新加的一个设置,对于IE8之外的浏览器是不识别的,这 ...