2015-10-15 37 views
5

我从博客中读到,当我们使用+运算符时,内部java使用StringBuilder来连接字符串。我只是检查它,发现一些奇怪的输出。How +在JAVA中的字符串内部工作

public class StringDemo { 

    public static void main(String[] args) { 

     String a = "Hello World"; 
     String b = "Hello World"; 
     String c = "Hello"; 
     String d = c + " World".intern(); 
     String e = new StringBuilder().append(String.valueOf(c)).append(" World").toString().intern() ; 
     String f = new StringBuilder(String.valueOf(c)).append(" World").toString().intern(); 

     System.out.println(a == b); // Line 1 Expected output true 
     System.out.println(a == d); // Line 2 Output is false 
     System.out.println(a == e); // Line 3 Output is true 
     System.out.println(a == f); // Line 4 Output is true 

    } 
} 

所以我用+运营商Concat的两个字符串Ç & “世界”,然后使用实习生()方法来在池中移动字符串字符串d

按我的理解Java的使用StringBuilder,所以现在我使用StringBuilder来Concat的字符串和使用实习生()方法用于字符串Ë˚F。 因此,如果两个字符串的等效地址都必须相同,但第二行的输出不符合第4行& 5.

在此先感谢您的宝贵意见。

回答

10

如何+在JAVA内部工作

这里是我的岗位上一样,给读Compiler version : How String concatenation works in java.

而来到你的代码中

System.out.println(a == d); 

这应该是只有false

根据您的理解,您期待true。不,你的理解是错误的。有

String d = c + " World".intern(); 

而且

String d = (c + " World").intern(); 

之间,第二行"Hello World"得到了实习

当你(c + " World").intern()有着明显的区别。在第一线只"World"得到了实习,你会看到输出true

+2

该死,小错。谢谢苏雷什 – Kick