Analysis of value passing and reference passing in Java

Source: Internet
Author: User

 Public classTest { Public Static voidMain (string[] args) {String s=NewString ("AAA");        Change (s);                System.out.println (s); StringBuilder SB=NewStringBuilder ("111");        Change (SB);    System.out.println (SB); }    Static voidChange (String s) {s=NewString ("BBB"); }    Static voidChange (StringBuilder sb) {sb.append ("333"); }}

Printing results:

Aaa
111333

=========================================================================================

As shown in the code above,

string s = new string ("AAA"), which is actually string s = "AAA", but the Java backend will automatically encapsulate it for us;

And here's the change (s), this is the value of the pass, the value of the transfer is actually a copy of the data (copy) does not affect the original value, in Java, 8 basic data types and string type Pass is a value pass.

==========================================================================================

Let's talk about reference delivery.

As shown in the code above,

StringBuilder sb = new StringBuilder ("111"); SB Point to New StringBuilder ("111")

Change (SB) is the time to pass the reference to SB, so when SB modifies the value, the original SB also follows the modification, because they point to the same piece of memory.

In Java, the transfer between objects is mostly a reference pass

===================================================================================

The above is my rough idea of the value passing and reference passing in Java, and you are welcome to guide and criticize the Great God.

Analysis of 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.