Java function parameters
It is easy to confuse whether java function parameters pass values or reference pairs. Most of the time, this problem may be blurred and may even cause some errors. The most common saying is that the basic type is to pass the value and the reference of the object. For the basic types, everyone has reached a consensus and there is nothing to argue about. However, for object transfer, it is also a value transfer. First, let's look at an example. A simple person class has only one property name and one personnel system. As follows:
public class Person{ private String name; public Persion(String name){ this.name = name; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; }}
Public class PersonnalSystem {public static void changeName1 (Persion person) {person. setName ("Bob"); System. out. println ("person name in changeName1:" person. getName (); // Bob, modified} public static void changeName2 (Persion person) {Person anotherPerson = new Persion ("Tom"); person = anotherPerson; System. out. println ("person name in changeName2:" person. getName (); // Tom modified} public static void main (String [] agrs) {Person person Person = new Persion ("Lily"); System. out. println ("before change name person's name is" + person. getName); // Lily changeName2 (person); System. out. println ("after first change name person's name is" + person. getName); // Bob changeName2 (person); System. out. println ("after second change name person's name is" + person. getName); // still Bob, not modified }}
Run this program and you can see that changeName1 modifies the person name, which is indeed a reference. However, although the person is successfully modified in the method when it is passed to changeName2, Bob is still not modified in the main function. This seems to be another value. This is because the object address is transmitted during object transmission, not the object reference or the copy of the object. Assume that the address of the person at the beginning is 60, and the parameter received by changeName1 is address 60, so the modification is made at address 60, so the object is changed. In changeName2, the address for creating an anotherPerson may be 65, but not 60. when anotherPerson is assigned to person, only 60 of the person code is changed to 65, and subsequent modification operations are performed at 65. Therefore, main (60) the person in is unaffected.
So in short, I think the java parameter passing process is value passing.
This method is also applicable to immutable types such as String, Integer, and Double. Because these objects are immutable, values are passed each time.Of course, it is not difficult to think that the object is a reference object, but it must first distinguish between immutable objects such as String and changeName2. In this case, do not expect the original object to be changed.