Value transfer or reference transfer?

Source: Internet
Author: User

The parameter transfer in Java, no matter what you pass, is only a copy passed in. This copy is saved as a local variable of the method in the stack.

If the data type is basic, modifying this value does not affect the variable passed in as a parameter, Because you modify the local variable of the method and it is a copy.

If an object is referenced, it is also the same as a copy, but the copy and the reference passed as a parameter point to the same object in the memory, so you can also operate on that object through this copy. However, if you modify the reference itself, such as directing it to another object in the memory, the reference originally passed as a parameter will not be affected. Therefore, only values are transmitted in Java.

Public class main {

Private Static void change (string S, stringbuffer SB ){

S = "aaaa ";

SB. setlength (0 );

SB. append ("aaaa ");

}

Public static void main (string [] ARGs ){

String S = "BBBB ";

Stringbuffer sb = new stringbuffer ("BBBB ");

Change (S, Sb );

System. Out. Print (S + Sb );

}

} // The output result is "bbbbaaaa" instead of "aaaaaaaa"

Public static void add (stringbuffer X, stringbuffer y ){

X. append (y );

Y = X;

}

Public static void main (string [] ARGs ){

Stringbuffer A = new stringbuffer ("");

Stringbuffer B = new stringbuffer ("B ");

Add (A, B );

System. Out. println (a + "," + B );

} // Output: AB, B

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.