A detailed discussion of Java reference delivery and value transfer

Source: Internet
Author: User
Tags java reference

The problem stems from a wide range of interview questions: When an object is passed as a parameter to a method, this method can change the properties of the object and return the result of the change, so is this a value pass or a reference pass?
In order to solve this problem, look up all kinds of data, but found that there is no uniform results, so only from my own point of view to give an answer. You are welcome to explore this issue.

According to Horstmann's "Java Core technology" (Chinese 8th edition p115-p117) Description, Java is not a reference to pass, the original excerpt is as follows:
The Java programming language always takes a value call. In other words, the method gets a copy of all the parameter values, especially if the method cannot modify the contents of any parameter variables passed to it. “

"Some programmers (even the authors of this book) think that the Java programming language uses reference calls to objects, which is actually wrong. ”

First, define the concepts of value passing and reference passing:
Value passing: Indicates that the method receives a value supplied by the caller.
Reference passing: Represents the variable address provided by the caller by the method.

In the following code, it is obvious that the value of the percent will not change.

    Double percent=10;
    Editpercent (percent);
    SYSTEM.OUT.PRINTLN ("percent after the end of the method:" +percent);

    public static void Editpercent (Double x) {
        x=3*x;
        System.out.println ("x:" +x in the method);
    }

In the following code, a Emplyee object is passed and the property of the employee object is changed by invoking the method.

    Employee boss= New Employee ("Boss", 5000);
    Editsalary (boss);

    public static void Editsalary (Employee x) {
        x.raisesalary);
        System.out.println ("Salary after end of method:" +x.getsalary ());
    }

The first piece of code, which executes the following procedure:
(1) x is initialized to a copy of the percent (10)
(2) x is multiplied by 3, but the percent is unchanged.
(3) After the method is finished, the parameter variable x is no longer used.

The second piece of code, which executes the following procedure:
(1) x is initialized to the boss copy, is a reference to an object
(2) Editsalary applies to this object's reference, when X modifies the object, when boss also references the same object, the object's salary is raised by 200%
(3) After the method is finished, the parameter variable x is no longer used, and boss continues to refer to the employee object that has been modified.

As you can see, when you pass an object parameter, Java refers to its operation in an approximate reference to the pass. This is also a key point in the debate. In fact, although there is no reference delivery in Java core technology, there are still many people who think that there is reference delivery in Java. Here is a highly contentious procedure.

public class Example {
    String str = new String ("good");
    char[] ch = {' A ', ' B ', ' C '};
    public static void Main (String args[]) {
        Example ex = new Example ();
        After the execution of this sentence
        Ex.change (ex.str, ex.ch);
        The str attribute of ex did not change, but the CH attribute was modified
        System.out.print (Ex.str + "and");
        System.out.print (ex.ch);
    }

    public void Change (String str, char ch[]) {
        str = ' Test ok ';
        Ch[0] = ' g ';
    }
}

What is the output of this program?

Good and GBC      Ch was modified by method while Str was not modified.

Obviously, both STR and ch[are object-passed, and the method is passed to a copy that references the object. So why char[] has been modified and string has not been modified.
The problem is

str= "Test OK"

Because of its particularity, the Copy object str in the method actually points to test OK after executing str= "test OK", while the original ex object still points to good and is not affected.
The copy of the char[] object directly modifies the contents of the char[0], when the properties and method copies of the ex object still point to the same object, so when the object is modified by the method copy, the ex is affected.

To sum up, parameter passing in Java is as follows:
• One method cannot modify a parameter of a basic data type
• One method can modify the state of an object parameter
• A method cannot be implemented so that object parameters refer to a new object

The following section of code in Java Core Technology explains why there is no reference delivery in Java: Write a method for exchanging objects:

Employee A=new Employee ("Tom", 7000);
Employee B=new Employee ("Jerry", 4000);

public static void Swap (employee X,employee y) {
    //Exchange two employees ' names
    employee temp=x;
    x=y;
    y=temp;
}

If Java uses a reference pass, then the swap method should be able to implement an exchange of two object values, but the end result is that swap does not change the object reference stored in a and B. The parameter x,y of the swap method is initialized to a copy of two object references, which swaps two copies and ultimately does not implement the result of the exchange.

Summary: Although there is a clear expression in the core technology that Java uses value transfer, Java is difficult to define whether a value pass or a reference is passed when it passes an object parameter to a method. After all, it's hard to say that passing an object parameter does not conform to the definition of a reference pass if you define it from a behavior.

Therefore, if the opening question is a simple answer, you can put your own understanding of the Java parameter pass calmly described clearly, I believe that the interviewer will give you a satisfactory score. If this problem is made into a multiple-choice question, different ways of understanding will have different answers, only that the interviewer is not fully prepared, even if the answer is wrong, it does not matter. Such a company, not to go, there is no good regret.

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.