java - 添加 String Literals 和 String 对象之间的区别

标签 java string literals

String Literal 和 String Object 的加法有什么区别?

例如

    String s1 ="hello";
    String s2 ="hello1";
    String s3 ="hello" + "hello1";
    String s4 ="hellohello1";
    String s5 = s1 + s2;

    System.out.println(s3 == s4); // returns true
    System.out.println(s3 == s5); // return false
    System.out.println(s4 == s5); // return false

为什么 s3/s4 没有指向与 s5 相同的位置?

最佳答案

因为 s1 + s2 不是常量表达式,因为 s1s2 不是 final,因此它的结果不会被保留,即创建另一个对象来表示它,因此引用比较会产生 false

JLS 3.10.5 String Literals :

String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

JLS 15.28 Constant Expression :

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • ...
  • Simple names that refer to constant variables (§4.12.4).

JLS 4.12.4定义 final 变量。

如果您将 s1s2 声明为 final,则 s3 == s5 将为 true

关于java - 添加 String Literals 和 String 对象之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649248/

相关文章:

string - 如何在 MATLAB 中搜索元胞数组中的字符串?

python - 在匹配另一个模式的字符串中找到最短子串的开始和结束索引

c++ - 文字运算符模板在 GCC 4.8 中不起作用

c - 如何将字符数组中的每个字符转换为整数?

java - 未报告的异常NegativeNumber;必须被捕获或宣布被扔出

java - 为什么创建一个新的int数组的结果等于5?

java - 线程中出现异常 "main"java.lang.NoClassDefFoundError : kotlin/KotlinPackage & Caused by: java. lang.ClassNotFoundException : kotlin. KotlinPackage

java - 通过左连接表/Querydsl 上的 QBean 映射具有 null 属性的对象

javascript - 使用函数结果读取 JS 中的对象文字

javascript - 如何在 JavaScript 中按字节反转字符串的顺序?