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. flex经验记录(转载)

    最近一直忙于项目,很好抽出时间学习,刚忙里偷闲浏览博客看到一位博友总结的一些flex的经验,感觉不错就转载过来,一来扩散一下,二来保存下来,以后忘记的时候可以回来学习下. 原博文地址:http://b ...

  2. 重拾HTML(一)

    一.网页组成 HTML:网页的具体内容和结构,由N个标签(节点,元素,标记)组成 CSS:网页的样式,美化网页 JavaScript:网页的交互效果,比如用户鼠标的点击事件作出响应   二.常见的HT ...

  3. mjrefresh源码分析

    最近想自己写个下拉刷新的库,但是始终感觉无从下手,想想总是容易的.原理也很简单,真正要下手写的时候,呵呵.不得不说ios封装得很好,网上可以用的成熟的库也很多,也正是因为如此很多开发者也忽略了很多底层 ...

  4. Duilib学习笔记《05》— 消息响应处理

    在Duilib学习笔记<04>中已经知道了如何将窗体显示出来,而如何处理窗体上的事件.消息呢? 一. 系统消息 窗体显示的时候我们就已经说了,窗体是继承CWindowWnd类的,对于窗体的 ...

  5. vyatta的fork开源版本

    https://www.reddit.com/r/networking/comments/3dvwfy/who_here_is_using_vyos/ Vyatta came in two flavo ...

  6. WP8_当滚动到滚动条的70%时,自动加载数据效果实现

    Touch.FrameReported += Touch_FrameReported;   void Touch_FrameReported(object sender, TouchFrameEven ...

  7. hdu1864

    use the cnt as the limit. #include <string.h> #include <stdio.h> ],sum; ]; double a,b,c; ...

  8. Largest palindrome product

    A palindromic number reads the same both ways. The largest palindrome made from the product of two 2 ...

  9. 自动发送EMAIL

    *&---------------------------------------------------------------------* *& Report  ZPP_SEND ...

  10. 第一章 Collections 类、泛型类和Timing类概述

    摘抄<数据结构与算法(C#语言描述)> 删除很多废话 1.1群集(collection)的定义 群集是一种结构化的数据类型.存储数据,并且提供数据的添.删.改操作,以及对群集不同属性值的设 ...