代码:
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; } }