String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes. This article summarizes whyString is designed to be immutable. A good answer depends on deep understanding of memory, synchronization, data structures, etc.

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. Caching 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. Facilitating the Use of Other Objects

To make this concrete, consider the following program:

HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
 
for(String a: set)
a.value = "a";

In this example, if String is mutable, it's value can be changed which would violate the design of set (set contains unduplicated elements). This example is designed for simplicity sake, in the real Stringclass there is no value field.

4. 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);
}

5. Immutable objects are naturally thread-safe

Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminate the requirements of doing synchronization.

In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.

reference from:http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/

Why String is immutable in Java ?--reference的更多相关文章

  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 ?

    This is an old yet still popular question. There are multiple reasons that String is designed to 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. java Reference

    相关讲解,参考: Java Reference 源码分析 Java Reference详解 Reference: // 名称说明下:Reference指代引用对象本身,Referent指代被引用对象 ...

  7. 为什么 String 是 immutable 类

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

  8. Java Reference简要概述

    @(Java)[Reference] Java Reference简要概述 Reference对象封装了其它对象的引用,可以和普通的对象一样操作. Java提供了四种不同类型的引用,引用级别从高到低分 ...

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

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

随机推荐

  1. function(a)

    问题:  问个初级的问题int a = 8;function(a);这里在function中的a值是引用a内存中的数据,还是新开辟内存后将a的值赋值到新内存供函数调用.  回答: int a = 8; ...

  2. Co-variant array conversion from x to y may cause run-time exception

    http://stackoverflow.com/questions/8704332/co-variant-array-conversion-from-x-to-y-may-cause-run-tim ...

  3. Form - 遍历行

    go_block('block_name'); first_record; LOOP   message(:block_name.item);   if :system.last_record  = ...

  4. Eclipse使用技巧及个性化设计

    以下除特殊说明均在 Windows->Preferences里面操作 如何把Eclipse关闭提示调出来? General->Startup and Shutdown,在 Confirm ...

  5. scp传入固件,sysupgrade xx.bin升级固件

    scp传入固件,sysupgrade xx.bin升级固件

  6. hadoop namenode启动过程详细剖析及瓶颈分析

    NameNode中几个关键的数据结构 FSImage Namenode 会将HDFS的文件和目录元数据存储在一个叫fsimage的二进制文件中,每次保存fsimage之后到下次保存之间的所有hdfs操 ...

  7. MapReduce的数据流程、执行流程

    MapReduce的数据流程: 预先加载本地的输入文件 经过MAP处理产生中间结果 经过shuffle程序将相同key的中间结果分发到同一节点上处理 Recude处理产生结果输出 将结果输出保存在hd ...

  8. Ruby应用记录:修改文件中某个字符串

    #修改android客户端中服务器地址的默认值为对应环境的服务器地址 #!/usr/bin/ruby ostr="192.168.88.95:8088" nstr="19 ...

  9. jQuery掷骰子

    网上找的jQuery掷骰子效果,测试兼容IE7及以上浏览器,IE6没有测试 js代码如下: $(function(){ var dice = $("#dice"); dice.cl ...

  10. Web---JSP注册技术的的演绎(3代)-JSP/EJB/Servlet/POJO/JavaBean

    我们可以这么理解JSP注册技术的发展过程: 第一代JSP技术:纯JSP开发. 第二代JSP技术:JSP+EJB开发. (EJB简单来说就是把已经编写好的程序(即:类)打包放在服务器上执行.) 第三代J ...