Java basic data type delivery differs from reference passing

Source: Internet
Author: User
Tags call by reference

Articles reproduced from Zejian's blog http://blog.csdn.net/javazejian/article/details/51192130

Java value Delivery and reference delivery are generally involved in interviews, and today we're going to talk about this, first of all we have to realize that this problem is generally relative to the function, that is, the method parameters in Java, So let's review the two professional terms in the programming language about parameters passed to methods (or functions):

    • Calling by value

    • Invoke by reference (call by reference)

The so-called call-to-value representation method receives the value provided by the call, whereas a call by reference means that the method receives the address of the variable provided by the caller (in the case of the C language, it is a pointer, and Java does not have a pointer concept, of course). Here we need to note that a method can modify the value of the variable to pass the reference, but not to modify the value of the variable passed the value of the call, which is very important, this is called by the value of the call and the reference to the fundamental difference, of course, if you do not understand, it is OK, the following will be illustrated thoroughly.

As we said before, there is no reference call in Java, which is true because the Java programming language does take a value call, called by values. This means that the method obtains a copy of all parameter values, and the method cannot modify the contents of any parameter variables passed to it. Let's look at an example:

Package com.zejian.test;  /**  * Call by value in Java  * @author Zejian */public  class Callbyvalue {            private static int x=10;            public static void Updatevalue (int value) {          value = 3 * value;      }            public static void Main (string[] args) {          System.out.println ("The value of the pre-call x:" +x);          Updatevalue (x);          System.out.println ("The value of the x after the call:" +x);}        }  

  

Run the program with the following results:

Value of the previous X call: 10

Value of x after call: 10

You can see that the value of x does not change, so let's take a look at the specific execution process:

Analysis:

1) value is initialized to a copy of the x value (that is, 10)

2) value is multiplied by 3 and equals 30, but note that at this point the value of x is still 10!

3) After this method is finished, the parameter variable value is no longer used and is recycled.

Conclusion: When passing method parameter types are basic data types (numbers and Boolean values), one method is not possible to modify the parameters of a base data type.

Of course, in Java, in addition to the basic data types and reference data types, which is the object reference, then what is the case for this data type? Let's just look at one example:

Declare a User object type:

Package com.zejian.test;  public class User {      private String name;      private int age;      Public User (String name, Int. age) {          this.name=name;          this.age=age;      }      Public String GetName () {          return name;      }      public void SetName (String name) {          this.name = name;      }      public int getage () {          return age;      }      public void Setage (int.) {          this.age = age;      }  }  

The execution classes are as follows:

Package com.zejian.test;  /**  * Call by value in Java  * @author Zejian */public  class Callbyvalue {      private static User user=null;      public static void UpdateUser (User student) {          student.setname ("Lishen");          Student.setage ();      }                  public static void Main (string[] args) {          user = new User ("Zhangsan", +);          System.out.println ("Value of user before call:" +user.tostring ());          UpdateUser (user);          System.out.println ("The value of user after invocation:" +user.tostring ());}  }  

  

The results of the operation are as follows:

Value of user before call: User [Name=zhangsan, age=26]

Value of user after invocation: User [Name=lishen, age=18]

Obviously, the value of the user is changed, that is, if the method parameter type is a reference type, the value corresponding to the reference type will be modified, let's analyze This process:

Process Analysis:

1) The student variable is initialized to a copy of the user value, and here is a reference to an object.

2) The Set method that invokes the student variable acts on the referenced object, and the internal values of the user object referenced by both user and student are modified.

3) After the method is finished, the student variable is no longer used, is freed, and the user remains unchanged, pointing to the user object.

Conclusion: When the pass-through method parameter type is a reference data type, a method modifies the value of the object pointed to by a parameter of the reference data type.

Although the transfer of the two data types is analyzed here, it is also understood that the transfer of the basic data type and the pass-through of the reference data type will not modify the value of the original data, while the latter will modify the value of the object pointed to by the reference. With the above example, we might think that Java has both call-by-value and invoke-by-reference, but it is a pity that such an understanding is misleading, although the reference-passing surface above refers to the invoke-by-reference phenomenon, but in Java it is true that only calls by value are not invoked by reference. It is estimated that quite a few people have been forced to do so, so let's take a counter-example to illustrate (recall the fundamental difference between the call by value and the call by reference, which we described at the beginning).

Package com.zejian.test;  /**  * Call by value in Java  * @author Zejian */public  class Callbyvalue {      private static User user=null;      private static User stu=null;            /**      * Swap two objects      * @param x      * @param y * * public      static void swap (user X,user y) {          user temp =x;
   x=y;          y=temp;      }                  public static void Main (string[] args) {          user = new User ("User", "n");          Stu = new User ("Stu");          System.out.println ("Value of user before call:" +user.tostring ());          System.out.println ("Stu Value before calling:" +stu.tostring ());          Swap (USER,STU);          System.out.println ("Value of user after invocation:" +user.tostring ());          System.out.println ("Value after call Stu:" +stu.tostring ());}  }  

  

We swapped two variables for the value of the user and the Stu by a swap function, as we said earlier, if it is called by reference, then a method can modify the value of the variable to pass the reference, that is, if Java is invoked by reference, then the Swap method will enable the exchange of data The actual running result is:

Value of user before call: User [Name=user, age=26]

Value before call Stu: User [Name=stu, age=18]

Value of user after invocation: User [Name=user, age=26]

Value of Stu after call: User [Name=stu, age=18]

We found that the value of user and Stu did not change, that is, the method did not change the object references stored in the variables user and Stu. The parameters x and y of the swap method are initialized to a copy of the two object references, and this method swaps the values of the two copies, and in the end, it's a waste of effort. X, Y will be discarded after the method ends, and the original variable user and Stu still refer to the object referenced before the method call.

This process also fully illustrates that the Java programming language is not referring to the object invocation, is actually the object reference is the value of the pass, of course, here we can simply understand that this is the difference between call by value and reference call, and must understand that even if the Java function in passing the reference data type, It's just a copy of the value of the reference, so the reference data can be modified because they point to an object at the same time, but this is still called by value rather than by reference.

Summarize:

      • A method cannot modify the parameters of a base data type (numeric and Boolean).

      • A method can modify the state of an object pointed to by a reference, but this is still called by value rather than by reference.

      • Both of the above passes have a value copy process.

Java basic data type delivery differs from reference passing

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.