Value passing and reference passing in Java

Source: Internet
Author: User

Figure out the concept of the two first.

Pass by value: means that when a parameter is passed to a function, the function receives a copy of the original value. Therefore, if the function modifies the parameter, only the copy is changed, and the original value remains unchanged.

Pass by reference: means that when a parameter is passed to a function, the function receives the memory address of the original value instead of a copy of the value. Therefore, if the function modifies the parameter, the original value in the calling code changes accordingly.

Function parameters:

1. The original data type is passed by value.

 Public class Test {    publicstaticvoid  main (string[] args) {        int i=1 ;        Change (i);        System.out.println (i);    }     Private Static void Change (int  var) {        //  TODO auto-generated method Stub        var=-var;    }}

Output: 1

2, the object is to pass the reference

 Public class Test {    publicstaticvoid  main (string[] args) {        person person = New Person ();        Person.i=1;        Change (person);        System.out.println (PERSON.I);    }     Private Static void Change (person tmp) {        //  TODO auto-generated method stub        tmp.i=100;    }}

Output: 100

Because the string type does not provide its own modified function, each operation is reborn as a string object, so it should be treated in a special way. Can be considered as a pass value.

done!

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.