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. 土法炼钢:怎么实现一个简单的B+Tree In-Disk

    1. 写在前面 说起B+树,大家应该都很熟悉.B+树是一种平衡的多路搜索树,广泛在操作系统和数据库系统用作索引.相比于内存的存取速度,磁盘I/O存取的开销要高上几个数量级.而将B+树用作索引时,它可以 ...

  2. nginx 编译模块说明

    --prefix= <path> - Nginx安装路径.如果没有指定,默认为 /usr/local/nginx. --sbin-path= <path> - Nginx可执行 ...

  3. asp.net(c#)修改时的赋值操作

    赋值操作方法(将信息显示至文本框中): public void Show_Infobase(int _peoid) { DataSet ds = new DataSet(); ds = platbll ...

  4. 使用UI Automation实现自动化测试 --工具使用

    当前项目进行三个多月了,好久也没有写日志了:空下点时间,补写下N久没写的日志 介绍下两个工具 我本人正常使用的UISpy.exe工具和inspect.exe工具 这是UISPY工具使用的图,正常使用到 ...

  5. java servlet上传文件并把文件内容显示在网页中

    servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象.下面我 ...

  6. PL/SQL中查询某的时间段内所有执行的sql

    清空缓存,重新开始统计执行的SQL alter system flush shared_pool; 查询执行过的SQL select * from v$sql where parsing_schema ...

  7. CLRS:median and order statistics

    //maximum and minimum     暴力遍历 O(n) //i-th element dicide and conquer random_selected_partition     ...

  8. 2016-03-10:libx265源码解析

    单步跟踪执行流程 将cli设定为启动项目,在属性->调试->命令行参数中设置如下参数: --input E:\video\pedestrian_area.yuv --fps 24 --in ...

  9. Oracle 通过触发器 来创建 同步临时表 及处理 通过 自治事务 来解决 查询 基表的问题

    // 触发器 create or replace trigger tr_sync_BD_MARBASCLASS after INSERT or UPDATE on BD_MARBASCLASS for ...

  10. php中使用end方法报错

    <b>Strict Standards</b>:  Only variables should be passed by reference in <b> 1.如果 ...