String里面除了hash这个参数不是final类型的之外,其余参数都是final类型的,String本质上是char[]数组的包装类,所以牵扯到内容变化的函数最后返回String类型的时候都是重新new了一个新的String类型出来,这跟原来传入的String参数就没什么关系了。
因此,我认为,当String作为参数传递时,确实是以地址传递过去的,但是在对String类型的变量的值进行改变时,由于String类的值是常量,在创建后不能更改,所以对String参数进行操作,相当于new String(),已经改变了String对象的地址了,所以实参不会改变。
public class TestString {
public static void main(String[] args) {
String s1 = new String("abc");
System.out.println("在main方法中s1的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s1)));
String s2 = new String("xyz");
System.out.println("在main方法中s2的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s2)));
show(s1, s2);
System.out.println(s1 + "-----" + s2);
System.out.println("在main方法中运行过show方法后s1的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s1)));
System.out.println("在main方法中运行过show方法后s2的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s2)));
}
static void show(String s1, String s2) {
s1 = s2 + s1 + "Q";
System.out.println("在show方法中s1的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s1)));
s2 = "W"+s1;
System.out.println("在show方法中s2的地址:" + String.class.getName() +
"@" + Integer.toHexString(System.identityHashCode(s2)));
}
}
运行结果:
在main方法中s1的地址:java.lang.String@1b6d3586
在main方法中s2的地址:java.lang.String@4554617c
在show方法中s1的地址:java.lang.String@74a14482
在show方法中s2的地址:java.lang.String@1540e19d
abc-----xyz
在main方法中运行过show方法后s1的地址:java.lang.String@1b6d3586
在main方法中运行过show方法后s2的地址:java.lang.String@4554617c
run可以发现,在show方法中,新new了s1和s2对象,和实参的地址已经不一样了。
Java打印String对象的地址参考自:



