为什么这里的字符串文字没有实习?

时间:2014-03-30 07:21:51

标签: 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 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行相同的字符串,因为我正在使用字符串文字   被安置在permgen空间。

更新: - 有没有办法可以强制编译器使用字符串文字而不是优化代码来使用新字符串?

3 个答案:

答案 0 :(得分:1)

您需要使用String类的intern()方法来获得所需的结果,这是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
  }
}

答案 1 :(得分:1)

this.str3 = str3 + 1; //line2

您正在运行时使用串联,它始终会创建一个新的String,默认情况下不会中断。您可以对此使用intern()方法,然后尝试进行比较。

String str2 = "testString" + 1; //line1

这是compile time constant expression,成功编译后将转换为

String str2 = "testString1";

这是一个字符串文字并将被实习。现在,在您的run方法中,您正在创建一个新的String,如前所述。因此两者都指向不同的String实例,因此==会给你错误。

答案 2 :(得分:0)

如果查看反编译代码,您应该在第2行看到下面的代码,因为编译器试图优化代码

  this.str3 = (new StringBuilder(String.valueOf(str3))).append(1).toString();

所以最后它使用new运算符创建了新的String对象,而toString()