java - java字符串不可变,但代码没有显示
问题描述
我正在学习字符串概念,所以写了一个代码,期望不同的输出,但得到了一些非常意想不到的东西。
class stringmute
{
public static void main(String[] args)
{
String s1="Hello "; //string one.
System.out.println("Str1:"+s1);
String s2= s1+"world"; //New String.
System.out.println("Str2="+s2);
s1=s1+"World!!"; //This should produce only Hello right?
System.out.println("Str1 modified:"+s1);
}
}
当我执行上面的代码时,我得到的输出为:
Str1:Hello
Str2=Hello world
Str1 modified:Hello World!!
如果我做错了什么,请告诉我。由于字符串是不可变的,这意味着我们应该将“Str1 Modified”的输出作为“HELLO”而不是“HELLO WORLD!!”。
解决方案
当您将 s1 分配为:
s1=s1+"World!!";
在 jvm 字符串池中创建新字符串并分配给 s1。
所以它的价值变成了“Hello World!!”
推荐阅读
- javascript - 在 NodeJS 模块内的此对象中找不到函数
- python - DRF - 覆盖 Serializer.update 以更新相关集
- sqlite - 编辑 SQLite3 数据库信息
- python - Python 3 中的 ModuleNotFoundError
- delphi - 在 OnUpdateRecord 事件中从 TFDUpdateSQL 读取结果
- dns - 如何为 digitalocean 设置子域?
- python - Python - is there a way to identify the directionality of angles?
- c# - 浏览器崩溃检测服务器端c#
- python - for filename in os.listdir FileNotFoundError: [Errno 2] No such file or directory
- prisma - 是否可以访问有关 prisma 模型的元数据?