【问题标题】:java strings inmutable but the code doesn't shows that [duplicate]java字符串不可变,但代码没有显示[重复]
【发布时间】:2019-01-08 02:38:16
【问题描述】:

我正在学习字符串概念,所以写了一个代码,期望不同的输出,但得到了一些非常意想不到的东西。

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

【问题讨论】:

标签: java string immutability


【解决方案1】:

当您将 s1 分配为:

s1=s1+"World!!";

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 2019-06-17
    • 2018-07-06
    • 1970-01-01
    • 2023-01-18
    • 2018-12-07
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多