为什么String在Java中是不可变的? [英] Why is String immutable in Java?

查看:290
本文介绍了为什么String在Java中是不可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在接受采访时被问到为什么String是不可变的

I was asked in an interview why String is immutable

我回答如下:


当我们在java中创建一个字符串,如 String s1 =hello; 然后将在字符串池中创建
对象(你好)
s1 将是
指向你好。现在我们再做一次 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 do String s2="hello"; then another object will not be created but s2 will point to hello 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.

如果我的回答是正确或错误

推荐答案

String 由于多种原因是不可变的,这里是摘要:

String is immutable for several reasons, here is a summary:


  • 安全性:参数是通常在网络连接,数据库连接URL,用户名/密码等中表示为 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).

这就是说,<不变性字符串仅表示您无法使用其公共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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆