再JAVA 中 String 这个类比较特殊,凡是新的String 对象并且赋值过,则不能改变该对象的值。
可以参考Java API中关于String的API
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);
所以有这样一段代码,大家可以参考一下
private void test(String obj){
obj="hello";
}
public static main(String args[]){
String x="hello world";
test(x);
System.out.println(x);
}
结果会是什么?答案应该就是“hello world”