(reprint) Understanding reference passing and value passing in Java

Source: Internet
Author: User
Tags object object stringbuffer

It is always a topic to talk about whether a reference pass or value is passed on a Java parameter.
There is a forum that there is only value in Java, there are some places that reference passing and value delivery are present, it is easier to confuse people.
About value passing and reference passing actually need to look at the situation, today study and analysis, anxious can first look at the final conclusion.

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 a primitive type holds the original value, that is, the value it represents is the value itself;
Whereas a variable of a reference type holds a reference value, the reference value points to the address of the memory space, which represents the reference to an object, not the object itself.
The object itself is stored at the location of the address represented by the reference value.

Basic types include: Byte,short,int,long,char,float,double,boolean,returnaddress,
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:

12 inta;a=10;//正确,因为声明a时就分配了空间

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

1234567 Date date;//执行实例化,开辟数据空间存放Date对象,然后把空间的首地址传给today变量 //date=new Date();//如果注释掉上一步操作//The local variable date may not have been initialized//也就是说对象的数据空间没有分配date.getDate();

  

Take a look at the following initialization procedure, Note that "references" are also space-consuming, and the reference size of an empty object object is about 4byte:

123 Date a,b; //在内存开辟两个引用空间a = newDate();//开辟存储Date对象的数据空间,并把该空间的首地址赋给ab = a; //将a存储空间中的地址写到b的存储空间中
3. Reference passing and value passing

The concept of actual parameters and formal parameters is used here to help understand,

Value passing:

When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the function receives a 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 parameter. Does not affect the value of the actual parameter .

Reference delivery:

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, and the function receives the memory address of the original value;
In the execution of the method, the parameters and the arguments are the same, pointing to the same memory address, and the operation of the reference in the method execution will affect the actual object .

See an example:

123 classMyObj{    public intb=99;}

pass int and object type separately:

1234567891011121314151617181920212223 publicclass ReferencePkValue2 {        publicstaticvoidmain(String[] args) {         ReferencePkValue2 t = newReferencePkValue2();         int a=99        t.test1(a);//这里传递的参数a就是按值传递         System.out.println(a);                MyObj obj=newMyObj();         t.test2(obj);//这里传递的参数obj就是引用传递        System.out.println(obj.b);            publicvoidtest1(inta){         a=a++;        System.out.println(a);                publicvoidtest2(MyObj obj){         obj.b=100;        System.out.println(obj.b);        }}

The output is:
99
99
100
100

As you can see, the int value does not change, but the changes made to the Obj class in the Test2 method affect the Obj object.

Here special consideration is given to string, and several basic types, such as Integer, double, are immutable types,
Because there is no function to provide its own modification, each operation is a new object, so special treatment, it can be considered to be similar to the basic data type, transfer value operation.

Look at the following example:

1234567891011121314151617181920212223 publicclassReferencePkValue1 {    publicstaticvoidmain(String[] args){        ReferencePkValue1 pk=newReferencePkValue1();        //String类似基本类型,值传递,不会改变实际参数的值        String test1="Hello";        pk.change(test1);        System.out.println(test1);                //StringBuffer和StringBuilder等是引用传递        StringBuffer test2=newStringBuffer("Hello");        pk.change(test2);                System.out.println(test2.toString());    }        publicvoidchange(String str){        str=str+"world";    }        public voidchange(StringBuffer str){        str.append("world");    }}

The output is:
Hello
Helloworld
The operation of string and StringBuffer produces different results.

4. Conclusion

In conjunction with the above analysis, the conclusion about value passing and reference passing can be drawn as follows:

(1) The basic data type transmission value, the modification of the formal parameters will not affect the actual parameters;
(2) Reference type is referenced, formal parameters and arguments point to the same memory address (the same object), so the modification of parameters will affect the actual object;
(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.

(reprint) Understanding 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.