@NoArgsConstructor @Getter @Setter public class Person { private Integer id; private String personName; public Person(String personName) { this.personName = personName; } }
public class TestTransferValue { public void changeValue1(int age) { age = 30; } public void changeValue2(Person person) { person.setPersonName("XXX"); } public void changeValue3(String str) { str = "XXX"; } public static void main(String[] args) { final TestTransferValue testTransferValue = new TestTransferValue(); int age = 20; testTransferValue.changeValue1(age); System.out.println("age------------" + age); final Person person = new Person("abc"); testTransferValue.changeValue2(person); System.out.println("person------" + person.getPersonName()); String str = "abc"; testTransferValue.changeValue3(str); System.out.println("person------" + str); } }
输出结果
age------------20
person------XXX
person------abc
age定义的位置是局部变量,基本数据类型传的是变量的副本,changeValue1不会改变原始变量的值
person引用数据类型传的是对象的引用,(指向同一个对象),changeValue2会改变变量的值
String 类型的引用类型存放在字符串常量池中,有则用之,无则创建