JAVA String 的又一个实例
看下面例子:
public class StringTest
{
public static void main(String[] args)
{
String str1 = "hello";
String str2 = "hel";
str2 = str2 + "lo";
System.out.println("str1 == str2 :" + (str1 == str2));
}
}
实际会打出false
{
public static void main(String[] args)
{
String str1 = "hello";
String str2 = "hel";
str2 = str2 + "lo";
System.out.println("str1 == str2 :" + (str1 == str2));
}
}
实际会打出false
为什么呢,关键就在于str2=str2+"lo"是不能能编译期就确定的
str1是在内存池没错,但str2不是~
用反编译工具反编译一下class文件就会发现
str2 =str2+"lo";
实际上是:
str2 = (new StringBuilder()).append(str2).append("lo").toString();
显然,str2是new出来的(不信去看看StringBuilder的源代码)
用反编译工具反编译一下class文件就会发现
str2 =str2+"lo";
实际上是:
str2 = (new StringBuilder()).append(str2).append("lo").toString();
显然,str2是new出来的(不信去看看StringBuilder的源代码)