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. ActionBar官方教程(7)自定义操作项的view,如何得到它及处理它的事件

    Adding an Action View An action view is a widget that appears in the action bar as a substitute for ...

  2. c#调用c++动态库的一些理解

    调用c++动态库一般我们这样写   [DllImport("UCamer.dll", CallingConvention = CallingConvention.Winapi)] ...

  3. 转自 z55250825 的几篇关于FFT的博文(三)

    题目大意:给出n个数qi,定义 Fj为        令 Ei=Fi/qi,求Ei.      其实这道题就是看到有FFT模板才觉得有必要学一下的...    所以实际上就是已经知道题解了... = ...

  4. DD_belatedPNG,IE6下PNG透明解决方案

    我们知道IE6是不支持透明的PNG的,这无疑限制了网页设计的发挥空间. 然而整个互联网上解决这个IE6的透明PNG的方案也是多不胜数,从使用IE特有的滤镜或是e­xpression,再到javascr ...

  5. Web.config配置文件详解(新手必看)

    花了点时间整理了一下ASP.NET Web.config配置文件的基本使用方法.很适合新手参看,由于Web.config在使用很灵活,可以自定义一些节点.所以这里只介绍一些比较常用的节点. <? ...

  6. HTML特殊字符大全2

    HTML的特殊字符我们并不常用,但是有的时候却要在页面中用到这些字符,甚至有时候还需要用这些字符来实现某种特殊的视觉效果.现在,国外的设计师Neal Chester整理了一份很全的特殊字符集,我觉得这 ...

  7. tomcat7 使用log4j进行日志记录

    将 tomcat-juli.jar 文件放置到 $CATALINA_BASE/bin 目录(实际上,该目录下已经有了) 从 log4j 网站下载 jar 包,并放置于 $CATALINA_BASE/l ...

  8. testng 注解

    testng.xml suite(套件):  由一个或多个测试组成 test(测试):  由一个或多个类组成 class(类):  一个或多个方法组成 @BeforeSuite: 在某个测试套件开始之 ...

  9. yarn环境的搭建

    1.首先,在zookeeper搭建成功,服务运行的基础上搭建yarn,其次,保证时间一致 2.在 /home/install/hadoop-2.5/etc/hadoop目录下配置一下几个配置文件: 第 ...

  10. linux驱动程序之电源管理之标准linux休眠与唤醒机制分析(一)

    1. Based on linux2.6.32,  only for mem(SDR) 2. 有兴趣请先参考阅读: 电源管理方案APM和ACPI比较.doc Linux系统的休眠与唤醒简介.doc 3 ...