Code Analysis:
Public class ParamTest {// The initial value is 0 protected int num = 0; // The public void change (int I) {I = 5;} is assigned to the method parameter again ;} // assign public void change (ParamTest t) {ParamTest tmp = new ParamTest (); tmp to the method parameter. num = 9; t = tmp;} // change the value of the method parameter public void add (int I) {I + = 10 ;} // change the public void add (ParamTest pt) {pt. num + = 20;} public static void main (String [] args) {ParamTest t = new ParamTest (); System. out. println ("parameter -- Basic Type"); System. out. println ("Original Value:" + t. num); // re-assign t for the basic type parameter. change (t. num); System. out. println ("after assignment:" + t. num); // value t for the referenced parameter. change (t); System. out. println ("after calculation:" + t. num); System. out. println (); t = new ParamTest (); System. out. println ("parameter -- reference type"); System. out. println ("Original Value:" + t. num); // change the value of the basic type parameter t. add (t. num); System. out. println ("after being referenced:" + t. num); // change the attribute value t of the object to which the reference type parameter points. add (t); System. out. println ("after modifying attributes:" + t. num );}}
The output result is as follows: parameter -- original value of the basic type: 0 after Value assignment: 0 after calculation: 0 parameter -- Original Value of the reference type: 0 after reference: 0 after attribute modification: 20. Conclusion: 1. when the basic type and basic type variables are passed as parameters to the method, they are passed as values. In a method object, you cannot assign a value to the original variable or change its value. 2. When an object or referenced variable is passed to a method as a parameter, the original variable cannot be assigned a value in the method object, but the attributes of the object to which it points can be changed. It does not matter whether it is a value transfer or a reference transfer. It is important to know what will happen in the method body when a reference is passed as a parameter to a method.