import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws Exception {
String title = "abc";
JFrame jframe = new JFrame(title);
jframe.setVisible(true);
title = "def";
}
}
运行此程序,最终title不会变为def,为什么呢?如此这般title的再改变已经不能再影响JFrame的title了,为什么呢?String是对象,java传的是引用,怎么会无效了呢?原因在于title第二次赋值之后,已经是一个新对象了,再上程序:
public class Test {
String string1 = "a";
String string2 = "b";
public static void main(String[] args) {
new Test().go();
}
public void go() {
change(string2);
string2 = "c";
System.out.println(string1);
}
public void change(String string2) {
string1 = string2;
}
}
这结果是b,说明没能改变
public class Test1 {
StringBuffer string1 = new StringBuffer("a");
StringBuffer string2 = new StringBuffer("b");
public static void main(String[] args) {
new Test1().go();
}
public void go() {
change(string2);
string2.replace(0, 1, "c");
System.out.println(string1);
}
public void change(StringBuffer string2) {
string1 = string2;
}
}
这结果是c,说明同一引用内容的改变影响到了,上图:
这是方法传参示意图,实参、形参的引用容易是两个不同的,但是彼此所盛装的引用指向是一致的,String被第二次赋值后,它所改变的已经不仅是内容了,而是引用本身了,已经是另外一个引用了,已不是指向原来 的String Object,因此无效。