昨天复习之前栈和堆课本时候偶然看到了一段代码在1jdk.8运行了。下面这段代码为什么change方法没有改变s1,s2,传进去的是引用对象,让s1,s2变量重新指向了新的对象或者常量池中的内容难道不应该被改变吗?
这块不太明白,我开始搞不清楚常量池是在栈还是在堆,因为离开方法区可能销毁对应的栈,所以为了确认我又改成了对象,
一定在堆中了,发现结果任然不变。希望有老师能给我点明白哪里想错了,谢谢老师。
代码1
public class Learn04 {
public static void main(String args[]){
String s1 = new String("abcd");
String s2 = "asdfghjkl";
System.out.println(s1+", "+s2);
change(s1,s2);
System.out.println(s1+", "+s2);
}
static void change(String s1,String s2){
s1 ="123456";
s2 ="000000";
System.out.println(s1+", "+s2);
}
}
代码2
public class Learn04 {
public static void main(String args[]){
String s1 = new String("abcd");
String s2 = "asdfghjkl";
System.out.println(s1+", "+s2);
change(s1,s2);
System.out.println(s1+", "+s2);
}
static void change(String s1,String s2){
s1 =new String("123456");
s2 =new String("000000");
System.out.println(s1+", "+s2);
}
}
实验结果: