我们来看下面的代码片段:
String s1 = "Hello";
String s2 = "Hello";
Run Code Online (Sandbox Code Playgroud)
由于实习,两个变量都引用同一个对象.由于字符串是不可变的,因此只创建一个对象并且它们都引用同一个对象.
A constant pool
也是一种东西,它包含在类中声明的所有常量(整数,字符串等).它是针对每个班级的.
System.out.println("Hello"); // I believe this Hello is different from above.
Run Code Online (Sandbox Code Playgroud)
问题:
string pool
在常量池中引用常量字符串对象的池?只需在jdk1.8(我的是 jdk1.8.0_60) 中运行以下代码,结果是:
true
false
true,
Run Code Online (Sandbox Code Playgroud)
方法c2()
返回false
,为什么?
我只想了解运行时常量池。不是比较不同的字符串。
public static void main(String[] args) throws InterruptedException {
c1();
c2();
c3();
}
private static void c1() {
String s1 = new String("a") + new String("b");
s1.intern();
String s2 = "ab";
System.out.println(s1 == s2);
}
private static void c2() {
String s1 = new String("h") + new String("e");
s1.intern();
String s2 = "he";
System.out.println(s1 == s2);
}
private static void c3() {
String s1 = new …
Run Code Online (Sandbox Code Playgroud)