Simply put, the scope of the reference variable s in the segment:
{ String s = new String("a string"); }
located between braces. This means that s exists only between opening and closing {}. However, something happens in this block.
In curly braces, the new operator is called to instantiate the String object. Memory is allocated for the object, and a reference to it is assigned to the variable s .
At the end of the code block, s no longer exists, and therefore the link that it holds no longer exists. However, the String object still exists in memory. But since there is no longer any variable that holds a reference to it, it is no longer available for any part of the program. At this stage, the facility has the right to garbage collection.
As long as the object does not collect garbage, it still occupies a stain in the system memory, even if it is no longer available for the program.
source share