这是您的 JLS 报价,第 3.10.5 节:
每个字符串文字都是对 String 类(第 4.3.3 节)实例(第 4.3.1 节、第 12.5 节)的引用(第 4.3 节)。字符串对象有一个常量值。字符串字面量——或者更一般地,作为常量表达式值的字符串(第 15.28 节)——是“内部的”,以便使用 String.intern 方法共享唯一的实例。
因此,由编译单元(§7.3)组成的测试程序:
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
和编译单元:
package other;
public class Other { static String hello = "Hello"; }
产生输出: true true true true false true
这个例子说明了六点:
同一包 (§7) 中同一类 (§8) 中的文字字符串表示对同一 String 对象 (§4.3.1) 的引用。
同一包中不同类中的文字字符串表示对同一 String 对象的引用。
不同包中不同类中的文字字符串同样表示对同一 String 对象的引用。
由常量表达式(第 15.28 节)计算的字符串在编译时计算,然后将其视为文字。
在运行时通过连接计算的字符串是新创建的,因此是不同的。显式实习计算字符串的结果是与任何具有相同内容的预先存在的文字字符串相同的字符串。
结合实习生的JavaDoc,您有足够的信息来推断您的两个案例都将返回 true。