Java – what happens to the lost string object
•
Java
Line 1: String x = "Java";
Line 1: String x = "Java"; Line 2: x.concat(" Rules!"); Line 3: System.out.println("x = " + x);
The output is "x = Java"
Line 1: create a new string object, give the value "Java", and reference x to it
Line 2: the VM creates a second string object with a value of "Java rules!" But there is no mention of it The second string object is about to be lost; You can't get it
Since these string objects are created in heap, the second object will be garbage collected
Solution
Enosh is immutable in Java strings, so you should allocate
x = x.concat(" Rules");
For the second line, then it will work
The second object will eventually be GC'd because no entity references it
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码