Java parameters, whether primitive or reference, are passed a copy of the parameter.
If the parameter type is the original type, then the passed parameter is a copy of the parameter, which is the value of the original parameter. If you change the value of a copy in a function, the original value is not changed.
If the parameter type is a reference type, the passed argument is a copy of the reference parameter, and two references point to the value of the same object. If the address of the copy is not changed in the function, it changes the
The value of the address, the changes within the function affect the parameters passed in. And if you change the address of the copy in the function, such as new, then the copy points to a new address, then the parameter passed to the original address,
All values that do not change the parameters. And if the value of the copy is changed in the function, and then the address of the copy is changed, such as New one, then the copy points to a new address, then the parameter passed to the original address,
However, the value of the parameter is changed.
Demo1:
1 Public classValuepass {2 3 Private Static intnum = 5;4 5 Public Static voidChangeValue (intN) {6 7n = n+2;8 9System.out.println ("n=" +n);Ten One } A - Public Static voidMain (string[] args) { - theSystem.out.println ("Before ChangeValue (), num=" +num); - - changevalue (num); - +System.out.println ("After ChangeValue (), num=" +num); - + } A at}
Demo2:
Public classReferencepass { Public Static voidChangesalary (Employ E,Doubleraisesalary) {e.setsalary (e.getsalary ()+raisesalary); System.out.println ("E.salary=" +e.getsalary ()); } Public Static voidChangeSalary2 (Employ E,Doubleraisesalary) {e.setsalary (e.getsalary ()+raisesalary); E.setsalary (E.getsalary ()+1000); Employ EE=Newemploy (); Ee.setsalary (20000); E=ee; System.out.println ("E.salary=" +e.getsalary ()); System.out.println ("Ee.salary=" +ee.getsalary ()); } Public Static voidMain (string[] args) {employ e=Newemploy (); E.setsalary (10000); System.out.println ("Before method, e.getsalary () =" +e.getsalary ()); Changesalary (E,1500); System.out.println ("After method, e.getsalary () =" +e.getsalary ()); ChangeSalary2 (E,1500); System.out.println ("After method, e.getsalary () =" +e.getsalary ()); }}classEmploy {Private Doublesalary; Public Doublegetsalary () {returnsalary; } Public voidSetsalary (Doublesalary) { This. Salary =salary; } }
Value passing and reference passing in Java