`

Why String is immutable in Java?

 
阅读更多

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 why String 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:
java-string-pool

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:

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

分享到:
评论

相关推荐

    Android代码-okio

    Okio Okio is a library that complements java.io and java.nio to make it ...ByteString is an immutable sequence of bytes. For character data, String is fundamental. ByteString is String's long-lost bro

    高效安全的Immutable List好处.docx

    Immutable List,顾名思义,就是,啥,不明白 Immutable 是什么意思?一成不变的意思,所以 Immutable List 就是一个不可变的 List 类,这意味着该 List 声明后,它的内容就是固定的,不可增删改的。 如果尝试对 ...

    is-immutable

    是不可变的 从公开isImmutable函数,但不包含Immutable库的其余部分。 用法 import isImmutable from 'is-immutable' ; isImmutable ( someObj ) ; // =&gt; boolean

    java-immutable-collections:Java的高效ImmutablePersistent集合

    Java的不可变集合 概述 Java库的不可变集合(JImmutable Collections)是一组高性能的不可变集合,用于替换或补充标准的java.util集合。 为每个最常用的集合提供功能替换: Java类 JImmutable接口 工厂方法 数组...

    Java 9 with JShell

    The release of Java 9 has brought many subtle and not-so-subtle changes to the way in which Java programmers approach their code. The most important ones are definitely the availability of a REPL, ...

    Immutable Collections for Java:不可变/永久性收藏库-开源

    提供Java不变/持久集合类的库。 尽管集合是不可变的,但它们提供了通过创建自身的新修改副本来添加和删除值的方法。 每个副本与其他副本尽可能共享其结构,以最大程度地减少内存消耗。 该库包括单链接(cons / cddr...

    JAVA不可变类(immutable)机制与String的不可变性(推荐)

    主要介绍了JAVA不可变类(immutable)机制与String的不可变性(推荐)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下

    IKM在线测试 JAVA 88题带参考答案

    最新最全的IKM在线测试题库,增加如下内容: spring ioc hibernate multiple questions Concurrency/Threadpool Exceptions HQL Query interface, Criteria in Hibernate SimpleDateFormat

    Docker and Immutable Infrastructure

    1.Overview of Docker the company and growth 2.Overview of Docker the latest stuff (DCUS announcements) & CaaS;...4.Docker and Immutable infrastructure/Microservices working together.

    java-immutable-collections:Java不可变的基于数组的集合

    ImmutableCollections-基于数组的Java不可变集合 版权所有(c)2017 Nicholas Cull 有关许可信息,请参阅LICENSE.txt。 Java 1.8的基于数组的不可变集合 排序和未排序的变体 风格类似于番石榴收集包装 空友好 Java 8...

    Android代码-kotlinx.collections.immutable

    What's in this library Interfaces and implementations This library provides interfaces for immutable persistent collections: Interface Bases Implementations ImmutableCollection Collection ...

    为什么Java字符串是不可变对象?

     流行的Java面试题之一是:什么是不可变对象(immutable object),不可变对象有什么好处,在什么情况下应该用,或者更具体一些,Java的String类为什么要设成immutable类型?  不可变对象,顾名思义是创建后不可以...

    技术分享之immutable.js.pptx

    简单介绍Immutable.js的一个ppt,主要用于技术分享,内容为imuutabe常用的数据类型和常用的基础api,还有immutable的原理、优缺点的分析。

    Java String 与 StringBuffer 用法区别

    String类用来表示那些创建后就不会再改变的字符串,它是immutable的。而StringBuffer类用来表示内容可变的字符串,并提供了修改底层字符串的方法

    javabiginteger源码-Java:Java

    java biginteger 源码 Java ...10. 为什么说String是immutable的?为什么不要多次循环中使用+=? 其value是加了哪个修饰语?其replace、append、trim等方法返回的值是什么? 11. hashCode使用了什么

    Java 9 Data Structures and Algorithms

    Debasish Ray Chawdhuri is an established Java developer and has been in the industry for the last 8 years. He has developed several systems, right from CRUD applications to programming languages and ...

    Mastering Immutable.js epub

    Mastering Immutable.js 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Cocoa Fundamentals Guide

    Why Mutable and Immutable Object Variants? 90 Programming with Mutable Objects 91 Class Clusters 95 Without Class Clusters: Simple Concept but Complex Interface 95 With Class Clusters: Simple Concept ...

    前端开源库-immutable-core

    前端开源库-immutable-core不变的核心,不变的模块化框架

    immutabilityutil一个开源immutabledata的轮子

    immutability-util:一个开源 immutable data 的轮子

Global site tag (gtag.js) - Google Analytics