Use the dog-painting method to explain the value transfer in Java

Source: Internet
Author: User

Before I start to see a puppy, let's take a look at a simple question:
What the output of the following program is.

If your answer is "Xiao Qiang", good, congratulations you are correct. Now let's change the code:

Yes, I just added a code to the ChangeName method.

What is the output this time?

A prosperous fortune

b Cockroach

The answer is a prosperous, changename method did not change the name of Mydog. If you're wrong, it doesn't matter, I'm going to start drawing the puppy, you'll understand if you get it right, but if you don't understand why, then my little dog will definitely help you. What's Mydog?

First you have to figure out what the variable Mydog in the code is. is Mydog really a dog? No. No. Mydog is just a dog rope for walking the dog.

In other words,Mydog is not the object that was put in the heap by new. Mydog is just a reference to this object instance (reference). If you know enough about the runtime data area of Java, you should be aware that this reference is placed on the virtual machine stack. parameter Passing

Now you know, Mydog is just a rope, but that doesn't seem to explain why the ChangeName method did not change the name of Mydog to "cockroach" because, according to the existing understanding, dog = new Dog (), is to tie my dog rope to another puppy, Then name the puppy "cockroach", like this:

But the truth is, Mydog is still called Richter, and that's why.
The problem is that on the method call, when I execute ChangeName (mydog) line of code, Mydog the dog string is copied, and the Dog Line (dog) that is passed into the ChangeName method is the one that is copied, like this:

Then execute dog= new Dog (), this line of code, is to copy out that a dog rope, from the Mydog untied, again tied to new out of the puppy, that is later named "Xiao Qiang" puppy:

and Mydog or tied to Richter body, which also explains why the implementation of the method out, Mydog.getname () or flourishing wealth. And in the first code, we do not execute dog= new Dog (), there is no change Dog tied to the puppy, Dog or tied to Richter body, so Dog.setname ("cockroach") will be the name of the prosperous wealth changed into a cockroach. Example of String

Let's look at one more example:

If you understand the example above, it should be easy to understand that in the Changestring method, only the newly copied reference, STR, points to another string constant object "BBB", the Str outside of the method body is not affected, or the string constant "AAA", So the final print is AAA. Examples of int

All of the above are objects, and here's an example of a basic data type

For basic data types, they have no references, but don't forget that when you call a function, the copy action will be done, and when you execute Changeint (i), I will copy the I to a new int and pass it to the Changeint method, so no matter what the inside of Changeint does to the join, The outside I will not be affected. The final print is still 1. value passing and reference passing

The above mentioned parameter transfer process in the copy operation, plainly, is = operation. The above int example, do the method inline, actually is this:

For basic data types, = operation copies the right variable (r_value) to the left variable (l_value), and to the object, exactly, it should be a reference to the object (like the mydog above), = The action is also to copy the right reference completely to the left reference. Both point to the same object instance.

This = operation, which is the fundamental difference between value passing and reference delivery , also leads to the following intuitive differences between value passing and reference passing:

If the parameter is a value pass, then the caller (outside of the method body) and the callee (method body part) use two different variables, and the changes in the method body in the face of the variable do not affect the variables outside the method body. In Java, you can change objects outside the method body within the method body, this is because the method body gets a reference to the object, but the reference is two different references to the reference outside the method body, and the reference inside the method body points to another object and does not cause the reference outside the method body to point to another object.

If the parameter is a reference pass, then the caller (outside of the method body) and the callee (method body part) use two identical variables, and changes in the method body face variables that affect the variables outside the method body. Java variables are not objects

With the above explanation, you also know a very important point:the variables in Java, either the basic data type, or point to the object instance of the reference type (dog rope), is definitely not an object (dog). Dog Rope and garbage collection

To understand the Mydog is just a dog rope (reference), but also help us understand the Java garbage collection mechanism, I mentioned in another article, once the JVM found an object and GC roots unreachable, the object will be recycled, look at the following code:

Now we know that the dog=null is just to cut off the dog rope so that the dog runs away and becomes a stray dog, just as the objects in Java are recycled as garbage:

Let's take a look at the cross references example:

If the JVM is using a reference notation, then dog 2 was previously referenced by DOG2 and Dog1.son two variables, and after dog2 = null, it was Dog1.son referenced, and dog 2 was not recycled.

But if we use the accessibility analysis, we'll find that the two dogs have no connection to the world, and even though they are both parent-child, the JVM has a mutual reference to this, but the object that has no association with GC roots is still recycled. Alternative methods for reference passing

There are two advantages to reference delivery:

Reference passing avoids copying when the method is invoked, especially when the method's entry is a large object, which consumes a lot of time and space, and of course Java has been cleverly solved, because for an object, the copy is only its reference;

Reference passing can modify external objects , which is why many languages support reference delivery.

So, in Java, how do you implement the "modify to the outside object" function like this.
The answer is to use the return value , similar to this:

Of course, if you just modify an object and then return to the new version of the object, consider moving the method into the object, like this:

Also, if you need to return multiple values, do not use the reference to pass, how to implement.

The answer is to return an object , such as you want to change the longitude and latitude of a place, so instead of passing in the log and lat two variables, wrap them inside the point object.

Above, hope to help you.

Do you have any ideas or opinions after reading this article? Welcome to leave a comment in the message area.

(You want to see what kind of push, welcome message to tell us)

More Wonderful

Programmer lifting appearance 丨 Wang Xiaobo programmer 丨 I will be programming 丨 Tanabata Express 丨 programmer highest honors 丨 program Ape (yuan) CP 丨 Heaven 丨 python lyrics 丨 Tesla 丨 program 丨 live 丨 chain 丨 knock code 丨 404 丨 Marriage 丨 Facebook 丨 How to enter bat 丨 girlfriend Diary 丨 high-Force guide 丨 Computer Professional 丨 Skills Dry Goods 丨 Jiuzhaigou Earthquake 丨 programming habits 丨 Lurkey Speech 丨 Self-Help guide 丨 Zhou Hongyi talk about entrepreneurship 丨


Public number Id:coder_life

Scan code focus on CSDN program life

The program Ape (yuan) 's exclusive public number

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.