代碼:
public class Demo { public static void main(String[] args) { // 引用傳遞示例 Student student = new Student(); student.setName("lisi"); student.setSex("girl"); new Method().test1(student); // entity的值發生了變化 System.out.println(student.getName() + "," + student.getSex()); // 輸出結果:zhangSan,boy // 值傳遞示例 // String傳遞的也是引用副本的傳遞,但是因為String為final的,所以和按值傳遞等同的 String str = new String("123"); new Method().test2(str); // str的值沒有發生變化 System.out.println(str); // 輸出結果: 123 } } class Method { /** * 引用傳遞 */ public void test1(Student entity) { entity.setName("zhangSan"); entity.setSex("boy"); } /** * 值傳遞 */ public void test2(String str) { str = "abc"; } } class Student { private String name; private String sex; public Student() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }