
java中static的调用练习,可以帮忙看看解释一下嘛,感谢感谢
下面是我的理解,供参考:
根据参考链接,应该是因为String是不可改变的,在show()方法中对形参s1和s2的赋值,实际上是将字符串拼接产生的新string对象的引用地址赋值给了形参s1和s2,main()方法中的s1和s2的引用地址是没有发生变化的,可以观察下赋值前后,s1和s2中的对象的地址及其值。
测试代码如下:
参考链接:
https://blog.csdn.net/zhouww969/article/details/78302552
https://blog.csdn.net/H_W_1212/article/details/104225873
https://blog.csdn.net/eydwyz/article/details/88861417
https://www.jianshu.com/p/a1433d48e5e4
public class StringDemo {
public static void main(String[] args) {
String s1="a";
String s2="b";
// https://www.jianshu.com/p/a1433d48e5e4
// 打印赋值前后,s1和s2的内存地址及其值,来观察程序的执行
System.out.println("in main(), before, s1_identityHashCode="+System.identityHashCode(s1)+", s1="+s1);
System.out.println("in main(), before, s2_identityHashCode="+System.identityHashCode(s2)+", s2="+s2);
show(s1,s2);
System.out.println(s1+s2);
System.out.println("\nin main(), after, s1_identityHashCode="+System.identityHashCode(s1)+", s1="+s1);
System.out.println("in main(), after, s2_identityHashCode="+System.identityHashCode(s2)+", s2="+s2);
}
// https://blog.csdn.net/zhouww969/article/details/78302552
// https://blog.csdn.net/H_W_1212/article/details/104225873
// https://blog.csdn.net/eydwyz/article/details/88861417
public static void show(String s1, String s2) {
System.out.println("\nin show(), before, s1_identityHashCode="+System.identityHashCode(s1)+", s1="+s1);
System.out.println("in show(), before, s2_identityHashCode="+System.identityHashCode(s2)+", s2="+s2);
s1=s1+"a";
s2=s2+s1;
System.out.println("\nin show(), after, s1_identityHashCode="+System.identityHashCode(s1)+", s1="+s1);
System.out.println("in show(), after, s2_identityHashCode="+System.identityHashCode(s2)+", s2="+s2);
}
}
