Reference passing and value passing in Java

Source: Internet
Author: User
Tags object object

1. Saving in memory for basic types and reference types
Data types in Java fall into two categories, basic types and object types. Accordingly, there are two types of variables: the base type and the reference type.
A variable of the underlying type holds the original value, that is, the value it represents is the number itself, whereas a variable of the reference type holds the reference value, the reference value points to the address of the memory space, represents a reference to an object, not the object itself, and the object itself is stored in the space of the address represented by the reference value.
The memory space of Java mainly includes 5 parts: Stack area, heap area, static variable or constant storage area, method area, local (native) method stack. As an example of a variable of reference type, the reference value is an address in the heap area, the reference value is saved in the stack, and the property of the object is stored in the address space pointed to by reference value within the heap area. The stack area follows the declaration cycle of the thread that called it, and the "reference value" of the heap area is no longer pointed to by the stack and is recycled by the GC.
The basic types are 8: Byte,short,int,long,char,float,double,boolean.
Reference types include: Class types, interface types, and arrays.
Accordingly, there are two types of variables: the base type and the reference type.

2. The difference between a variable's base type and a reference type
The basic data type allocates space to the system when it is declared:

int a;a=10;//is correct, because space is allocated when declaring a

The reference is different, and it declares that only the variable is assigned a reference space and no data space is allocated:

Date date;//opens a reference space in the stack memory date=new date ();//performs instantiation, opens up the data space to hold the date object, and then passes the first address of the space to the date variable

Note: The reference is also space-intensive, and the reference size of an empty object object is approximately 4byte:

Date A, B; In the stack memory open up two reference space A = new Date (),//In the heap memory to open the storage data space of the Date object, and assign the first address of the space to AB = A; To point B to an address in a storage space, which equals B and a together point to a storage space in the heap memory

3. Value passing and reference passing
The concept of actual parameters and formal parameters is used here to help understand,
(1) Value transfer:
When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the function receives a copy copy of the original value, at which time there are two equal basic types in memory, that is, the actual parameter and the formal parameter, and the operation in the subsequent method is the modification of the value of the formal parameter without affecting the value of the actual argument.
(2) Reference passing:
Also known as a pass-through address. When a method is called, the actual argument's reference (the address, not the value of the parameter) is passed to the corresponding formal parameter in the method, the function receives the memory address of the original value, and in the execution of the method, the parameter and the argument are the same, pointing to the same piece of memory address, and the operation of the reference in the execution of

Package com.itszt.test4;/** * Value passing and reference passing * Object Cloning */public class Referencepkvaluetest {public static void main (string[] Ar        GS) throws Clonenotsupportedexception {referencepkvaluetest test = new Referencepkvaluetest ();        MYOBJ obj=new MyObj ();        int a=99;        Test.test1 (a);        System.out.println ("Did not take the Clone Method-test2 () before execution, the attribute value in the object a_ref =" + Obj.geta ());        Test.test2 (obj);        System.out.println ("Does not take the Clone Method-test2 () after execution, the attribute value in the object a_ref =" + Obj.geta ());        System.out.println ("-----------------------");        int a_ref1 = Obj.geta ();        System.out.println ("Take Clone Method-before cloning, attribute value in Object a_ref1 =" + a_ref1);        Object Objclone = Obj.clone ();        if (objclone==null) {return;        } test.test2 ((MYOBJ) objclone);    System.out.println ("Take Clone Method-after cloning, attribute value in Object a_ref1 =" + a_ref1);        } private void Test1 (int a) {a+=1;    System.out.println ("A_val =" + a);        } private void Test2 (MyObj obj) {int a = Obj.geta (); Obj.seta (A+1);    System.out.println ("a_ref =" + a);    }}class MYOBJ implements cloneable{private int a=99;    public int Geta () {return A;    } public void SetA (int a) {this.a = A;    } @Override protected Object clone () throws Clonenotsupportedexception {return super.clone (); }}

After the code executes, the console prints as follows:

A_val = 100 did not take the Clone Method-test2 () before execution, the property value in the object a_ref = 99a_ref = 99 did not take the Clone Method-test2 () after execution, the property value in the object a_ref =----------------------- Take the Clone method-before cloning, the attribute value in the object a_ref1 = 100a_ref = 100 takes the Clone method-after cloning, the property value in the object A_REF1 = 100

In addition, we also need special consideration string, as well as the integer, double, and several basic types of wrapper class, they are immutable (immutable) type, because they do not provide a function for their own modification, each operation is a new object, so to be special treatment, Can be thought of as a value-based operation similar to the basic data type.

Package com.itszt.test4;/** * Basic types of wrapper classes, and string classes are passed with values like */public class ReferencePKValueTest2 {public static, when parameters are passed    void Main (string[] args) {        ReferencePKValueTest2 test2 = new ReferencePKValueTest2 ();        String similar to the base type of the value passed, does not change the value of the actual parameter        string string= "Hello";        Test2.change (string);        System.out.println (string);        StringBuffer and StringBuilder are referred to as        StringBuffer stringbuffer=new stringbuffer ("Hello");        Test2.change (StringBuffer);        System.out.println (Stringbuffer.tostring ());    }    public void Change (String str) {        str=str+ ' world ';    }    public void Change (StringBuffer str) {        str.append ("World");}    }

The console prints as follows:

Hellohelloworld

In general, with respect to value passing and reference passing, you can conclude that:
(1) The basic data type transmission value, the modification of the formal parameters will not affect the actual parameters;
(2) Reference types are referenced, formal parameters and arguments point to the same memory address (the same object), so the modification of the parameters will affect the actual object, if you want to circumvent the reference pass, you can use the cloning method;
(3) String, Integer, double, etc. immutable type special processing, can be understood as the value of the pass, the last operation will not modify the argument object.

Reference passing and value passing in Java

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.