我有这个代码
String a="test";
String b="test";
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
并且每个 Java 专家都知道,由于String pooling 设施if(a==b)
,这里将通过。
根据字符串池这就是为什么在上面的代码中条件已经通过。现在问题来了。在上面的代码中,当我添加了另外两行时,现在 String a & b 的值将是。新代码将是这样的
Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool
a+="1"
b+="1"
Test1
String a="test";
String b="test";
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
a+="1"; //it would be test1 now
b+="1"; //it would also be test1 now
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
现在在更改字符串之后,当我放置if(a==b)
检查时它没有通过。我知道这是由于字符串的不变性特性但我想知道
1)更改后,JVM 是否将它们与两个不同的对象一起存储?
2) JVM 是否要求new String()
更改任何字符串?
3)为什么即使我在更改时尝试调用它们也没有将它们作为单个引用intern()
?
Q3 提示:
a+="1".intern();
b+="1".intern();