为什么 String 在 Java 中是不可变的? [英] Why is String immutable in Java?
问题描述
我在一次采访中被问到为什么 String 是不可变的
I was asked in an interview why String is immutable
我是这样回答的:
当我们在 java 中创建一个像 String s1="hello";
这样的字符串时,然后一个对象将在 string pool(hello) 中创建,s1 将在指向 hello.现在如果我们再次执行 String s2="hello";
那么不会创建另一个对象,但 s2 将指向 hello
因为 JVM 会首先检查同一个对象是否存在于字符串池与否.如果不存在,则只创建一个新的,否则不创建.
When we create a string in java like
String s1="hello";
then an object will be created in string pool(hello) and s1 will be pointing to hello.Now if again we doString s2="hello";
then another object will not be created but s2 will point tohello
because JVM will first check if the same object is present in string pool or not.If not present then only a new one is created else not.
现在如果假设 java 允许字符串可变,那么如果我们将 s1 更改为 hello world
那么 s2 的值也将是 hello world
所以 java String 是不可变的.
Now if suppose java allows string mutable then if we change s1 to hello world
then s2 value will also be hello world
so java String is immutable.
谁能告诉我我的回答是正确还是错误?
Can any body please tell me if my answer is right or wrong?
推荐答案
String
是不可变的,原因有很多,总结如下:
String
is immutable for several reasons, here is a summary:
- 安全:参数在网络连接、数据库连接 URL、用户名/密码等中通常表示为
String
.如果它是可变的,则可以轻松更改这些参数. - 同步和并发:使 String 自动不可变使它们线程安全,从而解决同步问题.
- 缓存:当编译器优化您的 String 对象时,它会看到两个对象是否具有相同的值(a="test" 和 b="test"),因此您只需要一个字符串对象(对于 a 和 b,这两个将指向同一个对象).
- 类加载:
String
用作类加载的参数.如果是可变的,则可能会导致加载错误的类(因为可变对象会更改其状态).
- Security: parameters are typically represented as
String
in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed. - Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
- Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
- Class loading:
String
is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
话虽如此,String
的不变性仅意味着您无法使用其公共 API 更改它.实际上,您可以使用反射绕过普通 API.在此处查看答案.
That being said, immutability of String
only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.
在您的示例中,如果 String
是可变的,请考虑以下示例:
In your example, if String
was mutable, then consider the following example:
String a="stack";
System.out.println(a);//prints stack
a.setValue("overflow");
System.out.println(a);//if mutable it would print overflow
这篇关于为什么 String 在 Java 中是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!