Java 为什么这里不实习字符串文字?
这是我的主课Java 为什么这里不实习字符串文字?,java,string,Java,String,这是我的主课 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 ge
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行相同的字符串,因为我使用的是字符串文字
被拘留并储存在永久空间
更新:-有没有一种方法可以强制编译器使用字符串文字而不是优化代码以使用新字符串?如果您查看反编译代码,当编译器尝试优化代码时,您应该看到下面第2行的代码
this.str3 = (new StringBuilder(String.valueOf(str3))).append(1).toString();
因此,最后在toString()时使用new运算符创建新的String对象。您需要使用String类的方法来获得所需的结果,下面是TestThread的一个工作示例:
public class TestThread extends Thread {
String str3;
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(this.str3.intern() == str4.intern()){
System.out.println("Yes they are equal");
}else{
System.out.println("They are not equal");
}
}
@Override
public void run(){
// some processing
}
}
您正在运行时使用连接,它总是创建一个默认情况下不被插入的新字符串。您可以对此使用intern()
方法,然后尝试进行比较
String str2 = "testString" + 1; //line1
这是一个编译时常量表达式
,编译成功后将转换为
String str2 = "testString1";
这是一个字符串文本,将被插入。现在,在run方法中,您正在创建一个新字符串,正如我前面解释的那样。因此两者都指向不同的字符串实例,因此
=
将给出false。有没有办法强制编译器使用字符串文本而不是优化代码以使用新字符串?没有。第3行中没有可以使用的字符串文本。
String str2 = "testString1";