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"; |
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 String
class 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/
相关推荐
根据提供的信息,我们可以总结出这份Java基础String类选择题练习题主要聚焦于String及StringBuffer类的使用。尽管具体的题目内容未给出,但从所展示的信息中可以推断出该练习题集涵盖了以下几方面的知识点: ### 一...
Java 中的 String 类是一个特殊的类,它是一个 immutable 类,也就是说,一旦创建了 String 对象,它的值就不能被改变。String 类的 immutable 性质是通过 final 关键字实现的。 二、String 对象的创建 Java 中有...
`String`类是不可变的(immutable),这意味着一旦一个`String`对象被创建,它的内容就不能被改变。这种特性使得`String`类非常适合在多线程环境中使用,因为不需要担心其内容被多个线程同时修改。 #### 二、String...
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
这种方式创建的String对象位于常量池中,具有不可变性(immutable),即一旦创建后其内容就不能改变。 **1.2 使用new关键字** 另一种常见的初始化方法是使用`new`关键字: ```java String s = new String("hello")...
字符串一旦创建后不可改变,这是因为它被设计成不可变对象(`immutable object`)。Java中主要有两种方式来创建字符串: 1. **使用字符串常量直接初始化**: ```java String s = "hello!"; ``` 这种方式简单...
**一、什么是Immutable?** “Immutable”在编程中意味着一旦创建的数据对象就不能被修改。这种特性在JavaScript这样的动态语言中尤为重要,因为它可以防止意外的数据篡改,提高代码的预测性和安全性。Immutable.js...
"Java 中 Object 对象和 String 对象的解析" Java 中的 Object 对象和 String 对象是两个非常重要的概念。在 Java 中,每个对象都继承自 Object 对象,这意味着每个对象都拥有 Object 对象的方法和属性。String ...
What is immutable? **Answer**: An object is considered immutable if its state cannot be changed after it is created. In Java, the `String` class is a classic example of an immutable class. Once a `...
Java中的不可变类(immutable)是一种特殊的类,其对象一旦创建后,其状态就不能再发生变化。这类类在Java中有着重要的地位,特别是String类,它是Java中最常用的不可变类之一。不可变类的设计旨在提高安全性、效率...
`String`对象是不可变的(immutable),这意味着一旦一个`String`对象创建后,其内容不能被修改。这带来了几个关键的优势: 1. **线程安全**:由于`String`对象不可变,多个线程可以安全地共享同一个`String`对象,...
### Immutable Objects in Java 在Java编程语言中,不可变对象(Immutable Objects)是一个重要的概念,尤其是在构建健壮、易于维护的应用程序时。本篇将基于提供的文件内容来深入探讨不可变对象的概念及其在Java中...
是不可变的 从公开isImmutable函数,但不包含Immutable库的其余部分。 用法 import isImmutable from 'is-immutable' ; isImmutable ( someObj ) ; // => boolean
`String`类是Java中最基础也是最重要的数据类型之一,在Java中被定义为一个不可变类(immutable class),这意味着一旦一个`String`对象创建之后,其内容就不能再被修改。`String`类提供了丰富的内置方法来操作字符...
例如,使用 Immutable.js 库,可以使用 setIn 和 getIn 方法来更新和获取数据,而不是使用原生的赋值和获取方法。这样可以避免共享的可变状态问题,提高应用的性能和可维护性。 Immutable 是一种编程概念,可以解决...
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, ...
提供Java不变/持久集合类的库。 尽管集合是不可变的,但它们提供了通过创建自身的新修改副本来添加和删除值的方法。 每个副本与其他副本尽可能共享其结构,以最大程度地减少内存消耗。 该库包括单链接(cons / cddr...
Java中String对象具有不可变性(immutable)的特点,这意味着一旦创建了一个String对象,其内容就不能被更改。这种特性虽然确保了字符串的安全性和线程安全性,但也可能在某些情况下导致额外的内存消耗。因此,理解...