This question is based on Scope of Object chapter of Thinking in Java, 2nd edition, page 109 and it says that when we create a Java object using new it hangs around pass the end of scope. It gives this example:
{
String s = new String("a string");
} /* end of scope */
Then it says,
the reference s vanishes at the end of the scope. However, the String object that s was pointing to is still occupying memory. In this bit of code, there is no way to access the object because the only reference to it is out of scope.
So if I understand correctly, the text "a string" is still there in memory, but the pointer which has the memory address of the first character, 'a', does not exist. Is this what it meant?
It goes on to say,
It turns out that because objects created with new stay around for as long as you want them, a whole slew of C++ programming problems simply vanish in Java.
Why would this be advantageous? In the above example the string data continues to reside in memory with no way to access it (since the pointer was destroyed after it went out of scope ) which is only eating up resources.
In the Java programming language, the scope of variables or objects is determined by the position of the curly braces { }. A variable that is declared within the scope is available only in this scope.
In Java, once all references to an object have been nulled or fall out of scope the object itself becomes a candidate for destruction by the garbage collector. The GC does this automatically according to it's own algorithm whereas in C++ you'd have to explicitly destroy an object.
The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.
In Java, variables are only accessible inside the region they are created. This is called scope.
Put simply, the scope of the reference variable s
in the segment:
{
String s = new String("a string");
} /* end of scope */
is between the braces. This means that s
exists only between the opening and closing { }. Something happens in that block, however.
Within the braces, the new
operator is invoked to create an instance of a 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 so the reference it was holding no longer exists. The String
object, however, still exists in memory. But since there is no longer any variable that is holding a reference to it, it is no longer accessible to any part of the program. At this point, the object is eligible for garbage collection.
Until an object is garbage collected, it still occupies a spot in the system memory, even if it is no longer reachable by a program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With