毕业的学生在考scjp认证,问我怎么理解scjp的不变性。于是做了一个程序进了测试,对字符串的不变性理解如下:
class StringFinal
{
public static void main(String[] args)
{
String s="xxxxxxxHelloWord";
System.out.println(s+"地址"+s.hashCode());
s="how are you ";
System.out.println(s+"地址"+s.hashCode());
StringBuffer s1=new StringBuffer("xxxxhelloWord");
System.out.println(s1+"地址"+s1.hashCode());
s1.append("how are you");
System.out.println(s1+"地址"+s1.hashCode());
}
};
让学生观看结果,作如下总结:
一个字符串对象一但创建,那么这个字符串对象内容存放地址里面的内容就不能改变,
当对这个对象进行重新赋值时,系统会创建一个新的字符串对象,并把地址赋给原来的字
符串对象。因此s两次输出的址不一样,而s1两次输出的址是一样的。是否有不正确之处
还请高手指导。