"Reference" delivery of string in Java

Source: Internet
Author: User

1. Take a look at some interesting but confusing code snippets

 Public Static void Main (string[] args) {        new String ("AB");        Change (x);        SYSTEM.OUT.PRINTLN (x);    }          Public Static void Change (String x) {        = "CD";    }

Print Result: "AB"

2. What does this code really do? To explain the process.

First, when the string "AB" is created, Java allocates memory to store the string constant, and then the string constant is assigned to the variable x,x actually holds the reference address (in-memory address) of the string object, and the x variable holds the reference to the string object, and X is not the reference itself. It simply holds the reference address of the memory;

In Java, it is "value passing"; When X is passed to the change () method, a copy of the variable x is actually passed; the change () method creates a new string object "CD" and assigns a copy of the variable x, and the memory reference address of the "CD" Object is different!

3, how to solve this problem?

If we really want to change this object. First, this object must be mutable; second, you need to ensure that new objects are not created to be assigned to parametric variables, because Java is simply a value-passing

 Public Static void Main (string[] args) {    new StringBuilder ("AB");    Change (x);    SYSTEM.OUT.PRINTLN (x);    }           Public Static void Change (StringBuilder x) {        x.delete (0, 2). Append ("CD");    }

"Reference" delivery of string 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.