Value passing and reference passing in Java

Source: Internet
Author: User

When an object is passed as a parameter to a method, this method can change the properties of the object and return the changed result, is it a value pass or a reference pass?

A: the value is passed. The Java programming language has only value-passing parameters. When an object instance is passed as a parameter to a method, the value of the parameter is a copy of the object's reference. Point to the same object, the contents of the object can be changed in the called method, but the object's reference (not the referenced copy) is never changed.

Java parameters, whether primitive or reference, are passed as replicas (another argument is a pass value, but a copy is better understood, and the pass value is usually relative to the address).

If the parameter type is the original type, then a copy of the parameter is passed in, that is, the value of the original parameter, which is the same as the value that was previously discussed. If you change the value of a copy in a function, the original value is not changed ...

If the parameter type is a reference type, then a copy of the reference parameter is passed in, and the copy holds the address of the parameter. If you do not change the address of the copy in the function, but instead change the value in the address, the changes within the function will affect the parameters passed in. If you change the address of a copy in a function, such as new, the copy points to a new address, and the passed in parameter points to the original address, so the value of the parameter is not changed.

Example:

 Packagecom.demo.test; Public classEmployee {PrivateString name; Private Doublesalary;  PublicEmployee (String name,Doublesalary) {         This. Name =name;  This. Salary =salary; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public Doublegetsalary () {returnsalary; }     Public voidSetsalary (Doublesalary) {         This. Salary =salary; }}
 Packagecom.demo.test; Public classParamtest { Public Static voidMain (string[] args) {/*** Test 1:methods can ' t modify numeric parameters*/System.out.println ("Testing Triplevalue:"); DoublePercent = 10; System.out.println ("Before:percent=" +percent);        Triplevalue (percent); System.out.println ("After:percent=" +percent); /*** Test 2:methods can change the state of object parameters*/System.out.println ("\ntesting triplesalary:"); Employee Harry=NewEmployee ("Harry", 50000); System.out.println ("Before:salary=" +harry.getsalary ());        Triplesalary (Harry); System.out.println ("After:salary=" +harry.getsalary ()); /*** Test 3:methods can ' t attach new objects to object parameters*/System.out.println ("\ntesting Swap:"); Employee a=NewEmployee ("Alice", 70000); Employee b=NewEmployee ("Bob", 60000); System.out.println ("Before:a=" +a.getname ()); System.out.println ("Before:b=" +b.getname ());        Swap (A, b); System.out.println ("After:a=" +a.getname ()); System.out.println ("After:b=" +b.getname ()); }    Private Static voidSwap (employee x, employee y) {Employee temp=x; X=y; Y=temp; System.out.println ("End of method:x=" +x.getname ()); System.out.println ("End of method:y=" +y.getname ()); }    Private Static voidtriplesalary (Employee x) {x.setsalary (x.getsalary ()*); System.out.println ("End of method:salary=" +x.getsalary ()); }    Private Static voidTriplevalue (Doublex) {x= 3 *x; System.out.println ("End of Method x=" +x); }}

Operation Result:

testing tripleValue:Before:percent=10.0End of Method X= 30.0after:percent=10.0  Testing tripleSalary:Before:salary=50000.0End of method:salary=150000.0after:salary= 150000.0testing Swap:before:a=alicebefore:b=bobendof method:x =bob  // a copy of the visible reference is exchanged End of method:y=aliceafter:a=alice  // The reference itself is not exchanged After:b=bob

The first thing to note is that there is no pointer in Java, there is only value passing in Java, there is only value passing!!! However, we often see that the passing of objects (arrays, classes, interfaces) seems a bit like reference passing, which can change the value of an attribute in an object. But don't be fooled by this illusion, the value of the incoming function is actually a copy of the object reference, that is, the value of the referenced address is passed, so it is passed by value.

Example 1:

 Public class Test {    publicstaticvoid change (int  a) {        a=50;    }      Public Static void Main (string[] args) {        int a=10;        System.out.println (a);        Change (a);        System.out.println (a);    }}

It is clear that the output is 10, 10. A copy of the value is passed, which has nothing to do with the original value.

Memory Analysis:

Example 2:

 Public class Test {    publicstaticvoid change (int  []a) {        a[0]=50 ;    }      Public Static void Main (string[] args) {        int []a={10,20};        System.out.println (a[0]);        Change (a);        System.out.println (a[0]);}    }

The output result is obviously 10 50. The value of the referenced address is actually passed.

Memory Analysis:

Example 3:

classEMP { Public intAge ;}
Public classTest { Public Static voidChange (emp emp) {emp.age= 50; EMP=NewEMP ();//create an object againemp.age=100; } Public Static voidMain (string[] args) {emp emp=NewEmp (); Emp.age= 100; System.out.println (Emp.age); Change (EMP); System.out.println (Emp.age); System.out.println (Emp.age); }}

The output is: 100 50 50.

Memory Analysis:

For the String class:

 Public class Test {    publicstaticvoid change (String s) {        s= "Zhangsan";    }          Public Static void Main (string[] args) {        string s=new String ("Lisi");        System.out.println (s);        Change (s);        System.out.println (s);    }}

The output is: Lisi Lisi, because the string class is final decorated and immutable, it opens up a new space in memory.

Value passing and reference passing in Java

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.