Recently in reading Martin Fowler’s refactoring book, I saw in a chapter that JS parameter passing is passed by value, associated with Java. Let’s talk about Java parameter passing. Is it value passing or reference passing?
I still remember that when I was learning Java, my classmates asked me this question, and I confidently answered that of course, it was pass by value. Then I gave an example in code.
Output result:
oldAge is 100
change age is 10
Copy the code
Although my classmate thought my example was ok, he was not convinced by this conclusion, and gave another object example, indicating that Java parameter passing is passing by reference.
Program output result:
dog in method name is fill
main method dog name is fill
Copy the code
Indeed, this example changes the Dog object name property. After seeing it at that time, I felt that I had broken my cognition. Does Java transfer really follow the reference? Basic parameter types are only values. There is no such thing as an Object. Java objects are passed by value, while basic parameter types are passed by value.
I wonder if there are any friends who have the same confusion as me when they first learned Java? Ha ha.
Java parameter passing is passed by value, and the basic parameter type is the same as the object type.
For such an object creation procedure Dog Dog =new Dog(” Max “); In fact, the dog variable on the left-hand side of the equation is just a reference, while the real object on the right-hand side of the equal sign is located on the JVM heap.
Private static void foo(Dog foo) Declares an argument named foo in the foo method, which is initially assigned to null before being called.
When the foo method is called, the dog variable is passed, and then foo is assigned the heap address that dog actually points to, and the foo reference points to the actual parameter object.
Then in the foo method, you change the object name property.
Since foo and dog both refer to the same dog object, the output name attribute is fill.
Here’s another example.
The output of this example is:
dog in method name is fill
main method dog name is max
Copy the code
In this example, a new object is created in the method, and foo will point to the new object. Here we just change the reference to foo. So this results in a different output from the second example.
conclusion
Java parameter passing is value passing.