Analysis of value transfer and reference transfer in java, analysis of java transfer reference

Source: Internet
Author: User

Analysis of value transfer and reference transfer in java, analysis of java transfer reference

public class Test {    public static void main(String[] args) {        String s = new String("aaa");        change(s);        System.out.println(s);                StringBuilder sb = new StringBuilder("111");        change(sb);        System.out.println(sb);    }    static void change(String s){        s = new String("bbb");    }    static void change(StringBuilder sb){        sb.append("333");    }}

Print result:

Aaa
111333

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

As shown in the code above,

String s = new String ("aaa"); it is actually String s = "aaa"; but the java background will automatically encapsulate it for us;

The change (s) Here is the value transfer. The value transfer is actually a copy of the transmitted data and will not affect the original value, in java, the eight basic data types and the String type are passed as values.

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

Next we will talk about the transfer of references.

As shown in the code above,

StringBuilder sb = new StringBuilder ("111"); sb points to new StringBuilder ("111 ")

When you change (sb), the reference of sb is passed. So when sb modifies the value, the original sb is also modified because they point to the same memory.

In java, the transmission between objects is mostly reference transmission.

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

 

The above is my rough insight into the value transfer and reference transfer in java. You are welcome to give guidance and criticism.

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.