What are the parameters of methods in Java?
Many people believe that Java and C are the same: when a parameter is a basic data type, the value is passed and the parameter is passed as a reference pass-through address. Is that really the case?
First look at the paragraph code:
public class Snippet {public static void main (string[] args) {MyObj obj = new MYOBJ (); System.out.println (obj.age);p rocess (obj); System.out.println (obj.age);} private static void process (MyObj obj) {obj.age = 20;} Static class Myobj{private int age = 10;}}
The above code results everyone must understand: 10 20. Believe that there is reference in Java in the delivery of the person should be bewitched by such code, if the above parameter is passed by reference to pass the following code should be printed out what results?
public class Snippet {public static void main (string[] args) {MyObj obj = new MYOBJ (); System.out.println (obj.age);p rocess1 (obj); System.out.println (obj.age);} private static void process (MyObj obj) {obj.age = 20;} private static void Process1 (MyObj obj) {obj = new MyObj (); obj.age = 30;} Static class Myobj{private int age = 10;}}
If this is a reference pass, then calling the Process1 method will re-point the incoming reference to a new object and set the object's age to 30, and the program should run at 10 30, but the result is 10 10! Why is it? The answer is that there is only one form of parameter passing in Java-value passing!
How does a value pass work? The first piece of code calls:
The process method passes the reference copy of obj, which is the value that obj refers to, which is two references to the Obj object, and the process method changes the Age property of the object pointed to by the reference copy of obj to 20 and modifies the age of the object to which obj refers to. So the first piece of code is called after the print result is 10 20.
The second piece of code calls:
The Process1 method passes the "copy of Obj's reference" back to another object after "copy of Obj's reference" and changes the age of the new object to 30, and the new object is discarded after the method call is completed, of course, it has no effect on the reference to the obj used to print the data. , so the result is 10 10.
Problem of parameter Passing in Java