Summary of parameter passing problems in Java
Summary of parameter passing problems in Java
Start with two examples:
1)
Public class Test2 {
Public static void main (string [] ARGs ){
Stringbuffer A = new stringbuffer ("");
Stringbuffer B = new stringbuffer ("B ");
Operate (A, B );
System. Out. println (a + "," + B );
}
Static void operate (stringbuffer X, stringbuffer y ){
X. append (y );
Y = X;
}
}
Output: AB, B
2)
Public class Test2 {
Public static void add3 (integer I ){
Int val = I. intvalue ();
Val + = 3;
I = new INTEGER (VAL );
}
Public static void main (string ARGs []) {
Integer I = new INTEGER (0 );
Add3 (I );
System. Out. println (I. intvalue ());
}
}
Output: 0
First, we should understand that all parameter passing in Java is passed by value. If it is a basic type, copy a basic type to the input method. If it is a reference, copy a reference variable to the input method. If you understand these two points, you can understand the problems related to the method operation object. It is better to draw a picture pointing to an object to fully understand it.
Question 1st: When the operate method is called, two copies x and y that reference A and B are passed in. Both x and y point to the object referenced by the original A and B. X. append (y) performs operations on the object to which it points (that is, the object to which a points. X = Y, however, only two copy variables are assigned values, which does not affect the objects pointed to by original B. So the object that B points to is still B.
Question 2nd, I = new INTEGER (VAL) is just a reference copy pointing to another object, and the original I still points to the object new INTEGER (0.
If we grasp that all values in Java are transmitted and all the values are copied, we can solve similar problems.