有 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!!”


共 (1) 个答案

  1. # 1 楼答案

    当您将s1指定为:

    s1=s1+"World!!";
    

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

    所以它的价值变成了“你好,世界!!”