首页 > 解决方案 > 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!!”。

标签: javastringimmutability

解决方案


当您将 s1 分配为:

s1=s1+"World!!";

在 jvm 字符串池中创建新字符串并分配给 s1。

所以它的价值变成了“Hello World!!”


推荐阅读