`

【翻译】Why String is immutable in Java

阅读更多
原文地址: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html

This is one of the most popular interview question on String in Java which starts with discussion of What is immutable object , what are the benefits of immutable object , why do you use it and which scenarios do you use it.

It can also come once interviewee answers some preliminarily strings questions e.g. What is String pool , What is the difference between String and StringBuffer , What is the difference between StringBuffer and StringBuilder etc.

Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense

1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.

In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.

3)Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming.

I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post.


下面是一些回复:

(1)
sandeep said...

    Hi,

    I have a question regarding String Constant Pool.
    What will happend if the pool size reached its maximum limit?
    Wheather it will remove least recently used Strings or it wilol throws out of memory error or some GC will happen over unreferenced String object in the Constant pool
    January 18, 2011 2:20 AM
Javin @ Tibco RV Tutorial said...

    Hi Sandeep,

    As per my knowledge ,String pool gets created in PERM area of Java Heap , so if there are too many String there is good chance of OutOfMemoryError because garbage collection doesn't happen in PERM area of java heap.

    Thanks
    Javin
    January 19, 2011 3:59 AM
(2)
Sandeep said...

    Very good. I used to think of only the thread related reason. The other two are also quite valid.

    http://extreme-java.blogspot.com
    January 20, 2011 5:44 AM
Javin @ Tibco RV Tutorial said...

    Thanks Sandeep , Good to see you here back. Given extensive usage of String in any Java application and immutability benefit it provides as you pointed out which make it preferred choice in case of hashmap key or sharing between multiple thread everybody should know more about String Pool and behavior of String class.this is mine initiative
    January 20, 2011 6:40 AM
(3)
Dan Bergh Johnsson said...

    The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.

    Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter".
    January 21, 2011 12:39 PM
分享到:
评论

相关推荐

    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

    is-immutable

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

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

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

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

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

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

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

    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, ...

    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 ...

    技术分享之immutable.js.pptx

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

    Java String 与 StringBuffer 用法区别

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

    Mastering Immutable.js epub

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

    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 ...

    前端开源库-immutable-core

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

    immutabilityutil一个开源immutabledata的轮子

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

    前端开源库-immutable-ai

    前端开源库-immutable-ai不可变人工智能,不可变核心的可选接口

    高效安全的Immutable List好处.docx

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

    Immutable详解及React中实践.pdf

    Immutable详解及React中实践.pdf

    Collections源码java-java11-streams-laziness-needs-immutable-collections:使

    java11-streams-laziness-needs-immutable-collections 使用可变集合作为流源的示例可能会在处理过程中引起认知中断。 参考: 前言 流在几个方面与集合有所不同: 没有存储空间。 流不是存储元素的数据结构。 而是...

Global site tag (gtag.js) - Google Analytics