【问题标题】:Why the reference String str1 = str + "test " is different from String str3 = "checktest" [duplicate]为什么参考 String str1 = str + "test" 不同于 String str3 = "checktest" [重复]
【发布时间】:2019-09-22 16:18:55
【问题描述】:

为什么 str1==str2 在下面的代码中返回 false 而 str2 == str3 返回 true? 根据我的理解,str1==str2 也应该返回 true。

public static void main(String[] args) throws Exception {
        String str = "me";
        String str1 = str + "test";
        String str2 = "metest";
        String str3 = "me" + "test";
        System.out.println(str1==str2); // O/P false
        System.out.println(str2==str3); // O/P true

    }

【问题讨论】:

  • 如果strfinal,你会得到true。没有它,编译器不想假设 str 的值并将其评估留给运行时。如果它是最终编译器会在编译时知道它,所以它会在编译时简单地“计算”它,这意味着它会将str + "test" 视为"me" + "test"(就像str3)和只需将其编译为"metest"。在第二个副本中查看更多信息:Comparing strings with == which are declared final in Java

标签: java string


【解决方案1】:

字符串连接创建一个新字符串并将两个连接字符串的内容复制到它。这就是为什么。

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2022-08-12
    • 2021-11-07
    • 2019-02-12
    相关资源
    最近更新 更多