Understanding Java Reference

Source: Internet
Author: User
Tags java reference

Java World Rohit-class masterpiece "Thinking in Java" cut into Java and put forward "everything is Object". In Java, an object-filled world, reference is the root of all puzzles, and all the stories begin here.

What is reference?

If you were the same as me before you entered the Java world, you would never be unfamiliar with pointers to the wander world. Talking about pointers, the past all sorts of unbearable experience suddenly rushed to my heart, here is not the place to complain, let us temporarily forget the hands of the pain, recall the first touch of the sweet bar pointer! Remember how you read the textbooks, how to explain the pointers? One of the sayings that I remember is that the pointer is the address, just like the house number, with an address, you can easily find a family without having to do a haystack.

C + + On the stage of history, reference also followed, let me ask a small question, pointers and reference difference? My answer comes from the famous "more effective C + +" in the C + + world.

    1. There is no null reference.
    2. Reference must have an initial value.
    3. Using reference is more efficient than using pointers. Because reference does not need to test its validity.
    4. The pointer can be re-assigned, and reference always points to the object it originally obtained

Design options:

You should choose reference when you point to something that you need to point to, and never change to something else, or when you implement an operator whose syntax requires no pointers to be reached. At any other time, please use the pointer.

What does this have to do with Java?

Beginner Java, given the name of reference, I don't hesitate to equate it with the reference in C + +. However, I was wrong. In Java, reference can be arbitrarily assigned to empty, compared with the differences listed above, it is not difficult to find out, Java reference if you want to correspond to C + +, it is just a reference coat of hands.

So, all about C in the understanding of pointers, can be copied into Java, in short, reference is an address. We can think of it as a handle, grab it and grab the data we want to manipulate. As the key to mastering C is to master pointers, the key to exploring Java is reference.

A small program

I know that too much text is always sleepy, so let's get a piece of code!

public class Referencetricks {
public static void Main (string[] args) {
Referencetricks r = new Referencetricks ();
Reset integer
R.I = 0;
System.out.println ("Before Changeinteger:" + r.i);
Changeinteger (R);
System.out.println ("After Changeinteger:" + r.i);
Just for format
System.out.println ();
Reset integer
R.I = 0;
System.out.println ("Before changereference:" + r.i);
Changereference (R);
System.out.println ("After changereference:" + r.i);
}

private static void Changereference (Referencetricks r) {
R = new Referencetricks ();
R.I = 5;
System.out.println ("in changereference:" + r.i);
}

private static void Changeinteger (Referencetricks r) {
R.I = 5;
System.out.println ("in Changeinteger:" + r.i);
}

public int i;
}

Sorry, I know, setting a field to public is a bad coding habit, just to illustrate the problem.

If you are interested in running this program yourself, I am waiting for you!

OK, have you run it already? What's the result? Is it as you expect? Here are the results I ran on my own machine:

Before changeinteger:0
Geinteger:5
Hangeinteger:5
changereference:0
Gereference:5

Here, we are interested in two change--changereference and Changeinteger. From the content of the output, we can see that two methods are exactly the same as before and in the call, and the difference occurs after the result of the call.

a confused explanation

Let us first analyze the behavior of Changeinteger.

As I said earlier, reference in Java is an address that points to a memory space that holds information about an object. Here we temporarily do not care about how this memory is arranged, as long as we know that through the address, we can find the R object of the I field, and then we assign it to 5. Since the contents of this field have been modified and returned from the function, it is naturally the result of the change, so after the call, the I field of the R object is still 5. Shows the memory changes before and after the Changeinteger call.

Reference +--------+ Reference +--------+

---------->|               i = 0 | ---------->| i = 5 |

|--------| |--------|

|                          Memory | | Memory |

|                          |        | |

|                          |        | |

+--------+                          +--------+

After calling Changereference before calling Changereferenc

Let's turn our eyes to changereference.

From the code, we can see that the difference between the same changeinteger is just a lot more.

R = new Referencetricks ();

The purpose of this statement is to allocate a new piece of memory and then point R to it.

After executing this statement, R is no longer the original R, but it is still a Referencetricks object, so we can still assign a value to the I field of this r. So far, everything is so natural.

Reference +--------+ +--------+

---------->|                          i = 0 | | i = 0 |

|--------| |--------|

|                          Memory | | Memory |

|                | Reference |--------|

|               | ---------->| i = 5 |

+--------+                          +--------+

After calling Changereference before calling Changereferenc

Follow this idea to continue, after executing the changereference, output R of the I field, then should be the new memory I, so should be 5. As for the memory that we abandoned, the GC function of Java will naturally clean up for us.

Backfired.

The actual results we have seen, the output is 0.

It must be wrong, which is where?

The Secret of parameter passing

Do you know how to pass method parameters?

When I first started to learn programming, the teacher taught that the parameters, the formal parameters and the actual parameters, those written in the parameter list are called formal parameters, they are replaced by actual parameters when actually called.

The compiler is not likely to know what the actual parameters of each call are, so the master of the compiler to write a method, so that the actual parameters in a certain order to be placed in a place that everyone can find, as a method call a convention. The so-called "no rules, inadequate surrounding area", with this rule, it is much easier for everyone to work together. This common data area, now the compiler's choice is usually "stack", and the so-called order is the formal parameter declaration order.

Obviously, the process of running the program, as the actual parameters of the variable may be scattered in the memory of the various locations, and do not have to honestly stay in the stack. In order to keep the "rules", the program had to copy the variables to the stack, which is what is usually said to push the parameters into the stack.

With a spirit, the answer will be revealed.

What did I just say? Copy the variable to the stack, yes, "copy"!

This is called a value pass.

In the first chapter of the "C programming Language", the classic of C, when it comes to actual parameters, "in C, the actual parameters of all functions are passed ' value '".

Soon someone will stand out, "wrong, and the address, such as a pointer to pass the address."

Yes, the pass pointer is the address. When you think of a pointer as an address, do you consider the question, which is also a variable. As mentioned in the previous discussion, parameter passing must be pressed into the stack, and the pointer to the address is no exception. Therefore, the pointer must also be copied. In the function, the pointer operation is actually an operation for this pointer copy.

Java reference is equal to the C pointer. So, in the Java method call, reference also copies a copy of the stack. The operation of the reference in the method is the operation of the reference copy.

Mystery revealed

OK, let's go back to the original question.

The assignment to reference in Changereference is actually a copy of the reference, and it has no effect on the reference of the Buddha.

Back to the point of call, the Buddha woke up, it did not know what had happened during the time they slept, so had to be as if nothing had happened in general. In this way, the copy disappears, and the modifications to it in the method are dissipated.

Perhaps you will ask the question, "After listening to your explanation, I am confused about Changeinteger, since it is for the operation of the copy, why Changeinteger can work properly?" "

Oh, very interesting short-circuit phenomenon of the brain.

OK, so I'll explain the operation of Changeinteger in the previous statement.

The result of the so-called reproduction is necessarily that the copy is exactly the same as the Buddha. The result of reference replication is necessarily that two reference point to the same piece of memory space.

Although the operation of the copy in the method does not affect the Buddha, the changes to the memory space are real.

Back to the call point, although the Buddha still does not know what has happened, but it is in the original way to access the memory when it is indeed after the method modified content.

The method can then extend its influence beyond the method.

Demo download

Just a few more words.

This problem originated from my thinking about the same problem in C/C + +. In C/C + +, the assignment of reference in Changereference may not have serious consequences, whereas doing so will cause the infamous "memory leak" of the Java, which is simply due to the lovely GC functionality. Even so, I still do not recommend the use of this approach, after all, the GC is already very busy, how can we have the nerve to trouble others.

This problem can continue to be extended in the C + +. Since the direct assignment of pointers in a function doesn't work, how do you modify pointers in a function? The answer is very simple, the pointer pointer, that is, the original pointer as a normal data, a pointer to its hand to the function.

The same problem is that there is no such thing as a wonderful solution in Java, because there is no such syntax as reference reference in Java. A possible workaround is to encapsulate the reference into classes. As far as value is worth, justice is at ease.

Reference documents

1 "Thinking in Java"

2 "more effective C + +"

3 "The C programming Language"

Reprinted from

Understanding Java Reference

Related Article

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.