请参考以下文档: The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc";
is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data);
str1 = null;
不会有问题
{
public static void main(String[] args)
{
String str1 = "String";
String str2 = str1;
System.out.println(str2);
str1 = null;
System.out.println(str2);
}
}D:\test>java test
String
String
不知道你是怎么操作的
String str2 = str1;
str1 = null;
在执行第2句后,str2实际上是对"1234567"做了引用,而不是对str1做了引用。虽然此时str1也引用"1234567"。所以此时清空str1,没有任何问题。
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);