Java - 奇怪的静态字符串行为 - 新字符串(“xxx”) vs “xxx”
2022-09-03 04:39:50
public class Test {
private static final String str1 = new String("en");
private static Test instance = initInstance();
private static final String str2 = new String("en");
private static final String str3 = "en";
private Test() {
}
public static void main(String[] args) {
}
private static Test initInstance() {
instance = new Test();
System.out.println(str1 + ',' + str2 + ',' + str3);
return instance;
}
}
从理论上讲,静态无处不在,它应该导致“en,en,en”。
结果: “en,null,en”
预期:“en,null,null”(因为我发现静态顺序实际上很重要)
有人能解释一下吗?“en”和new String(“en”)有什么不同?