这里是我的主类为什么在这里字符串字面不被禁用?
public class MainClass {
public static void main(String args[]) {
String str1 = "testString";
String str2 = "testString" + 1; //line1
//above literal value(i.e str2 = "testString1") is interned and stored in permamnent generation space
//now when whenever i create "testString1" down the line in this program, it should refer from same location
//but it does not seem true
TestThread tt= new TestThread(str1, str2);
tt.start();
}
}
这里是我的线程类
package Test;
public class TestThread extends Thread {
String str2;
public TestThread(String str3, String str4) {
this.str3 = str3 + 1; //line2
System.out.println("value inside Thread is "+this.str3);
System.out.println("value inside Thread is "+str4);
if(str3 == str4){
System.out.println("Yes they are equal");
}else{
System.out.println("They are not equal");
}
//line 3
@Override
public void run(){
// some processing
}
}
在第3行, “他们是不是等于” 被打印出来。但为什么 ?第2行应该引用与第1行相同的字符串,因为我使用的字符串文字 被interned并存储在permgen空间中。
更新: -有没有一种方法可以强制编译器使用字符串文字,而不是优化代码使用新的字符串?
有没有办法我可以强制编译器使用字符串文字而不是优化代码来使用新的字符串? – user3198603
否。可以使用第3行没有字符串文字。 – Jorn