這裏是我的主類爲什麼在這裏字符串字面不被禁用?
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