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 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"; |
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>(); |
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){
|
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的更多相关文章
- 为什么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 ...
- Why string is immutable in Java ?
This is an old yet still popular question. There are multiple reasons that String is designed to be ...
- 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 ...
- JAVA —— String is immutable. What exactly is the meaning? [duplicate]
question: I wrote the following code on immutable Strings. public class ImmutableStrings { public st ...
- JAVA 中为什么String 是immutable的
本文翻译自:http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/ 这是一个很老但很流行的问题,这里有几个原因Stri ...
- java Reference
相关讲解,参考: Java Reference 源码分析 Java Reference详解 Reference: // 名称说明下:Reference指代引用对象本身,Referent指代被引用对象 ...
- 为什么 String 是 immutable 类
二哥,你能给我说说为什么 String 是 immutable 类(不可变对象)吗?我想研究它,想知道为什么它就不可变了,这种强烈的愿望就像想研究浩瀚的星空一样.但无奈自身功力有限,始终觉得雾里看花终 ...
- Java Reference简要概述
@(Java)[Reference] Java Reference简要概述 Reference对象封装了其它对象的引用,可以和普通的对象一样操作. Java提供了四种不同类型的引用,引用级别从高到低分 ...
- 前台传参数时间类型不匹配:type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'
springMVC action接收参数: org.springframework.validation.BindException: org.springframework.validation.B ...
随机推荐
- mybatis UpdateByExampleMapper UpdateByExampleSelectiveMapper
/** * 通用Mapper接口,Example查询 * * @param <T> 不能为空 * @author liuzh */ public interface UpdateByExa ...
- 测试ODBC与OLE
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data. ...
- 3 Financial Services Social Media Success Storie
As financial services firms step-up their use of social media, we’ve been looking for some early suc ...
- CodeForces 1
A- Theatre Square Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u ...
- UpdatePanel无法直接弹出窗口的解决
UpdatePanel无法直接弹出窗口的解决 2010-06-20 来自:博客园 字体大小:[大 中 小] 摘要:本文介绍一些UpdatePanel无法直接弹出窗口的解决方法 ///<sum ...
- aspx页面记住密码
界面 点击登录按钮的代码 protected void btnLogin_Click(object sender, EventArgs e) { if (remember_long.Checked) ...
- asp.net基础
这篇主要讲述以下基础知识: Request对象 Response对象 Server对象 Cookie对象 Application对象 ViewState对象 <%%>与<%=%> ...
- Asp.Net MVC4新特性指南(2):新特性介绍
上一章讲解了最基本的MVC4说明.今天就介绍下几种新特性的使用例子: 就当大家有MVC3的基础了.在这个基础上在看下面的介绍就容易多了.1.Web API MVC4包括一个更好的解决方案:A ...
- 《HTML5与CSS3基础教程》笔记
以下笔记摘要页码基于 人民邮电出版社 2013年1月第1版 英文书名:HMTL5 and CSS3 Visual Quickstart Guide (Seven Edition) 前言 P2: 渐进增 ...
- CodeForces 361B Levko and Permutation
题意:有n个数,这些数的范围是[1,n],并且每个数都是不相同的.你需要构造一个排列,使得这个排列上的数与它所在位置的序号的最大公约数满足 > 1,并且这些数的个数恰好满足k个,输出这样的一个排 ...