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