Why is it that only value in Java is passed----convince yourself

Source: Internet
Author: User

It is necessary to correct some of the previous misconceptions before we begin to dive into the explanation. If you have the following ideas, then you need to read this article carefully.

Error understanding one: value passing and reference passing, the condition of distinction is the content of passing, if it is a value, it is the value passing. If it is a reference, it is a reference pass.

Error Understanding two: Java is a reference pass.

Error understanding three: The passed parameter if it is a normal type, that is the value of the pass, if it is an object, that is the reference to pass.

Real participation Formal parameters

As we all know, when defining a method in Java, you can define the parameters. For example, the main method in Java:

public static void main(String[] args)

The args in this is the parameter. The parameters are divided into formal parameters and actual parameters in the program language.

Formal parameters: Parameters that are used when defining function names and body functions to receive the arguments passed in when the function is called.

Actual parameters: When a parameter function is called, there is a data transfer relationship between the key function and the tuned function. When a function is called in the keynote function, the arguments in parentheses after the function name are called "actual arguments."

A simple example:

public static void main(String[] args) {
   ParamTest pt = new ParamTest();
   pt.sout("Hollis");//实际参数为 Hollis
}

public void sout(String name) { //形式参数为 name
   System.out.println(name);
}

The actual parameter is what is actually passed when the parameter is called, and the formal parameter is the parameter used to receive the actual parameter content.

Value passing and reference passing

As mentioned above, when we invoke an argument function, we pass the actual parameter to the formal parameter. However, in a programming language, there are two cases passed during this pass, that is, value passing and reference passing. Let's look at how the program language defines and distinguishes between value passing and reference passing.

A value pass (pass by value) refers to a copy of the actual argument to the function when the function is called, so that if the parameter is modified in the function, the actual argument will not be affected.

Reference passing (pass by reference) means that the address of the actual parameter is passed directly to the function when the function is called, and the modification of the parameter in the function will affect the actual parameter.

With the concept above, and then you can write code practice, to see whether Java is the value of passing or reference delivery, so the simplest piece of code out:

public static void main(String[] args) {
   ParamTest pt = new ParamTest();

   int i = 10;
   pt.pass(i );
   System.out.println("print in main , i is " + i);
}

public void pass(int j) {
   j = 20;
   System.out.println("print in pass , j is " + j);
}

In the above code, we modify the value of the parameter J in the Pass method, and then print the value of the parameter separately in the pass method and the main method. The output results are as follows:

print in pass , j is 20
print in main , i is 10

As can be seen, the change to the value of name inside the pass method does not change the value of the actual parameter I. So, according to the definition above, someone gets the conclusion that Java's method passing is a value pass.

However, it was soon questioned (haha, so don't jump to conclusions.) )。 They will then move out the following code:

   public     static     void     Main ( string[) args)   {
   paramtest pt =   new  paramtest ();

   user hollis =   new  user ();
   hollis.setname ( "Hollis");
   hollis.setgender ( "Male");
   pt.pass (Hollis);
   system. out.println ( "Print in Main, user is"  + Hollis);
}

public   void   Pass ( user user)  {
   user.setname ( "Hollischuang");
   system. out.println ( "Print in Pass, user is"  + user);
}

It is also a pass method, which also modifies the value of the parameter within the pass method. The output results are as follows:

print in pass , user is User{name=‘hollischuang‘, gender=‘Male‘}
print in main , user is User{name=‘hollischuang‘, gender=‘Male‘}

After the pass method is executed, the value of the argument is changed, that is, according to the definition passed above, the value of the actual parameter is changed, this is not a reference to pass. Therefore, according to the above two code, someone came to a new conclusion: Java method, when passing the ordinary type is the value of the pass, when passing the object type is a reference to pass.

However, this statement is still wrong. I don't believe you. This parameter type is passed as a parameter to the object:

public static void main(String[] args) {
   ParamTest pt = new ParamTest();

   String name = "Hollis";
   pt.pass(name);
   System.out.println("print in main , name is " + name);
}

public void pass(String name) {
   name = "hollischuang";
   System.out.println("print in pass , name is " + name);
}

The above code outputs the result as

print in pass , name is hollischuang
print in main , name is Hollis

What is the explanation for this? An object is also passed, but the value of the original parameter is not modified, and the passed object becomes a value pass?

Value Passing in Java

Above, we give three examples, the results are different, this is also caused by many beginners, and even many senior programmers for the Java delivery type is confusing reasons.

In fact, I would like to tell you that the above concept is not wrong, but the code example is problematic. Here, let me draw a few more ideas about the concept, and then give you some really good examples.

A value pass (pass by value) refers to a copy of the actual argument to the function when the function is called, so that if the parameter is modified in the function, the actual argument will not be affected.

Reference passing (pass by reference) means that the address of the actual parameter is passed directly to the function when the function is called, and the modification of the parameter in the function will affect the actual parameter.

So, let me summarize, what is the point of the difference between value passing and reference passing.

In the example of several passes we have seen above, we have only focused on whether the actual parameter content has changed. If the user object is passed, we try to change the value of his Name property and check for changes. In fact, in the experimental method is wrong, of course, the conclusion will be a problem.

Why is it that the experimental method is wrong? Here we give an example of an image. Take a closer look at value passing and reference passing, and you'll know why it's wrong.

You have a key, and when your friend wants to go to your house, if you give him your key directly, that's the quote pass. In this case, if he has done something about the key, such as if he had carved his name on the key, then the key will be given to you, and your own key would have been engraved with his name.

You have a key, when your friend wants to go to your house, you re-carved a new key to him, his own hand, this is the value of delivery. In this case, what he does with the key will not affect the key in your hand.

However, whatever the case, your friend takes the key you gave him and enters your home, smashing your TV. Do you think you will be affected? When we change the value of the Name property of the user object in the Pass method, it is not "smashing the TV". You changed not the key, but the house where the key was opened.

Also take an example of the above, we 真正的改变参数 , see what happens?

PublicStaticvoid  Main ( string[) args)   {
   paramtest pt =   New   Paramtest ();

   user hollis =   new  user ();
   hollis.setname ( "Hollis");
   hollis.setgender ( "Male");
   pt.pass (Hollis);
   system. out.println ( "Print in Main, user is"  + Hollis);
}

public   void   Pass ( user user)  {
   user =   new  user ();
   user.setname ( "Hollischuang");
   user.setgender ( "Male");
   system. out.println ( "Print in Pass, user is"  + user);
}

In the above code, we change the user object in the Pass method, and the output is as follows:

print in pass , user is User{name=‘hollischuang‘, gender=‘Male‘}
print in main , user is User{name=‘Hollis‘, gender=‘Male‘}

Let's draw a picture and see what happens in the process, and then I'll tell you why there is only value in Java.

To explain this diagram a little bit, when we create a user object in main, we open up a piece of memory in the heap, which holds data such as name and gender. The Hollis then holds the address of the memory 0x123456 (Figure 1).

When an attempt is made to call the pass method and the Hollis is passed as the actual parameter to the form parameter user, the address is given to the 0x123456 user, and the user points to the address (Figure 2).

Then, when the parameters are modified within the pass method, that is user = new User(); , the memory is re-opened and assigned to the 0X456789 user. Any subsequent changes to the user will not alter 0X123456 the contents of the memory (Figure 3).

What is the delivery of the above? It is certainly not a reference pass, and if it is a reference pass, the reference to the actual parameter should also be pointed to when the user = new user () is executed, 0X456789 but not actually.

Through the concept we can also know that here is a reference to the actual parameters of the address copied a copy , passed to the formal parameters. So, the above argument is actually a value pass, and the address referenced by the argument object is passed as a value to the formal parameter.

Let's look back at the example of "smashing the TV" before, and see what happens in the delivery process in that example.

Similarly, in the process of parameter passing, the address of the actual argument 0X1213456 is copied to the formal parameter, except that in this method, the parameter itself is not modified, but the modified parameter holds the content stored in the address.

Therefore, the difference between a value pass and a reference pass is not what is passed. But whether the argument has been copied to a formal parameter. when judging the content of the argument is not affected, to see what is transmitted, if you pass an address, then see if the change of the address will have an impact, rather than see the address of the object changes. It's like the relationship between the key and the house.

So, in this case, why is the same as passing objects, the string object passed and the user object is not the same result? We used the pass method name = "hollischuang"; to try to change the value of name, quirks directly changed the address of the reference of name. Because this code, a string is new, and the reference is given to name, which is equivalent to:

name = new String("hollischuang");

The original "Hollis" string is still held by the argument, so the value of the actual parameter is not modified.

So, in Java, the value is actually passed, but for the object parameter, the content of the value is a reference to the object.

Summarize

whether it is a value pass or a reference pass, it is actually an evaluation strategy (Evaluation strategy). in the evaluation strategy, there is another called by share delivery (call by sharing). In fact, the parameter passing in Java is strictly in the sense that it should be passed by share.

Pass by share refers to a copy of the address of an argument that is passed to the function when the function is called, such as the fruit parameter in the stack, and the value is copied directly. When you manipulate parameters inside a function, you need to copy the address to find the exact value before you manipulate it. If the value is in the stack, then because it is a direct copy of the value, the function's internal manipulation of the parameters does not affect the external variables. If the original value is copied to the address in the heap, then the corresponding location in the heap needs to be found based on the address before the operation. Because the copy of the address is passed, the operation of the value inside the function is visible to the external variable.

Simply put, the pass in Java is a value pass, and this value is actually a reference to the object.

by sharing the pass is actually just a special case of passing by value. so we can say that the delivery of Java is passed by share, or that the delivery in Java is a value pass.

Why is it that only value in Java is passed----convince yourself

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.