Java中的值传递和引用传递
在java中实质只存在一种传递方式:即值传递。 而引用传递是对C/C++而言的。结论:
对于基本类型,在方法体内对方法参数进行重新赋值,并不会改变原有变量的值。
对于引用类型,在方法体内对方法参数进行重新赋予引用,并不会改变原有变量所持有的引用。
方法体内对参数进行运算,不影响原有变量的值。
方法体内对参数所指向对象的属性进行运算,将改变原有变量所指向对象的属性值。
在JAVA中变量有以下两种:
基本类型变量,包括char、byte、short、int、long、float、double、boolean。
引用类型变量,包括类、接口、数组(基本类型数组和对象数组)。
最后我们得出如下的结论:
基本类型和基本类型变量被当作参数传递给方法时,是值传递。在方法实体中,无法给原变量重新赋值,也无法改变它的值。
对象和引用型变量被当作参数传递给方法时,在方法实体中,无法给原变量重新赋值,但是可以改变它所指向对象的属性。
以下是代码片段: 2 public class Person 3 { 4 private String name = null; 5 private int age = 0; 6 7 public Person(String name, int age) { 8 this.name = name; 9 this.age = age; 10 } 11 12 public void changeName(String newName) { 13 this.name = newName; 14 } 15 16 public void changeAge(int newAge) { 17 this.age = newAge; 18 } 19 20 public String toString() { 21 return "Person - Name: " + name + ", Age: " + age; 22 } 23 } 24 25 public class PassByValue 26 { 27 public static void main(String[] args) { 28 // one example 29 String value1 = "value1: aaa"; 30 String value2 = "value2: bbb"; 31 32 swapValue(value1, value2); 33 34 System.out.println(value1); 35 System.out.println(value2); 36 37 // another example 38 Person person = new Person("张三", 20); 39 40 System.out.println(person.toString()); 41 42 changePerson(person); 43 44 System.out.println(person.toString()); 45 } 46 47 public static void swapValue(String tmpValue1, String tmpValue2) { 48 String tempStr = tmpValue1; 49 tmpValue1 = tmpValue2; 50 tmpValue2 = tempStr; 51 } 52 53 public static void changePerson(Person tmpPerson) { 54 tmpPerson.changeName("李四"); 55 tmpPerson.changeAge(30); 56 } 57 } 58 |