7

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.

1
  • The Garbage collector comes to save the Java Runtime resources when such situation occurs. Do not worry, you will get the space back after next garbage collection is triggered :)
    – dharam
    Jul 15, 2013 at 5:33

8 Answers 8

3

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.

3
  • Isn't this what happens in C as well, difference being there is no garbage collector? Then what did "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." mean?
    – user13267
    Jul 15, 2013 at 5:33
  • It's true, memory is not managed 'out of the box' in C like it is in Java (among other things). But it's hard to compare C to Java in this case because Java is an object-oriented paradigm from the ground up, whereas C works with objects only as an extension. In C, unless you're working with some kind of library to manage memory, when the block ends you would need to reclaim or deallocate the memory that you had allocated for the String object that was created.
    – scottb
    Jul 15, 2013 at 5:39
  • And wat with this? String s; void fillString(String m){ s = new String(m); } fillString("foo"); fillString("bar"); What with object "foo" if you called fillString("bar")
    – Jomme
    Jan 9, 2019 at 23:12
2

Once Object is out of scope and it will be ready for garbage collection untill GC collect the detached object, will occupy the memory.

8
  • Isn't it ready for garbage collection as soon as it is out of scope?
    – user13267
    Jul 15, 2013 at 5:23
  • yes it is, GC run on daemon thread, every time it will not immediately collect it Jul 15, 2013 at 5:24
  • besides, isn't this the same thing that happens in C? After object goes out of scope, what was there in the memory still remains there. The difference in Java is that there is a garbage collector built in, while in C/C++ there is not. So what does the line "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." mean?
    – user13267
    Jul 15, 2013 at 5:25
  • In C++, you have to use delete to remove the object from memory, while in java, JVM takes care of this. If you write C++ code, you can understand, you are not very clear how many objects you have created and when you should use delete to clear it. This is a great stragedy that we abstract all the static things and use mechine to do it and we just mind the dynamic thing.
    – OQJF
    Jul 15, 2013 at 5:28
  • 1
    @user13267 In other words, the author probably meant "It turns out that because objects created with new stay around for at least as long as you need them and doesn't necessarily exist after you need it, a whole slew of C++ programming problems simply vanish in Java".
    – zEro
    Jul 15, 2013 at 5:36
2

Turn to page 215 to read about How a garbage collector works.

While the Java code is running, the Garbage Collector runs periodically to find all the objects that are not being references and free the memory occupied by them. When this happens, the finalize method is called on your object (if defined). At that time you do any cleanup required by your object.

With c++, you must worry about freeing memory yourself using the delete keyword - failure to do so can result in memory leaks.

With Java, you are trading management of memory allocation for managed object lifecycle management.

4
  • what did this line in particular mean? "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."
    – user13267
    Jul 15, 2013 at 5:31
  • "As long as you want them" means <while they are being referenced>. Once all the references to your object are out of scope, its assumed you no longer want it and it is cleaned up.
    – Andrew
    Jul 15, 2013 at 5:35
  • is there any example for them not being around in C/C++, even while we are using them?
    – user13267
    Jul 15, 2013 at 5:38
  • Sure, you delete an object and then afterwards try to access it, say by dereferencing a pointer to it.
    – Andrew
    Jul 15, 2013 at 5:44
1

Well it resides in memory until the Java Garbage Collector cleans it up for you. Which it does periodically. Meaning you do not have to manage the memory yourself.

You can create objects without having to worry about allocating and deallocating memory.

1

Since the object is out of scope , it will be automatically garbage collected by java garbage collector. It is advantageous then C++ because, in java, Java Runtime, will automatically take care of Garbage collection, so eventually the memory will be reclaimed. This is not the case with C++

1

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. Additionally, the String may continue to exist due to what's called interning.

1

I don't understand the point the book is trying to make when it talks about blocks of code still occupying memory. Perhaps what it is trying to say is that just because a reference variable (like s in the example) goes out of scope, it doesn't mean that the memory is released immediately. What it fails to say (at least in what you posted), is that such memory is subject to automatic garbage collection and, in fact, you should program as if such orphaned memory blocks will be collected.

The great thing about garbage collection in Java as compared to C++ is that it is all done automatically. When all strong references (including all indirect references) to a memory allocation go out of scope, then that memory block is subject to automatic garbage collection. That's it in a nutshell. Java correctly handles things like circular references and will garbage collect arbitrarily complex data structures, provided the structure is not accessible either directly or indirectly from any reference value still in scope.

Also, there are special rules for strings because of interning, so the book kind of failed with that example.

2
  • It does talk about garbage collection in the paragraph that immediately follows. What I don't understand is, isn't this the same thing that happens in C/C++ as well? Variable goes out of scope, but what it wrote in memory still stays there? The difference in Java is that it has a garbage collector while C/C++ does not. Then what does "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." mean?
    – user13267
    Jul 15, 2013 at 5:28
  • @user13267 - I'm just not sure what they mean. Perhaps they're referring to C++, objects that can be allocated on the stack; such memory is returned to the system when the variable goes out of scope. In Java, all objects are allocated on the heap and such behavior does not occur; objects remain alive as long as you have references to them, after which they become subject to gc.
    – Ted Hopp
    Jul 15, 2013 at 5:33
0

What was meant is that the object is not "lying around" it is still in memory waiting to be collected by the garbage collector. Think about it like this. You have many objects in your house and you want to get rid of some of them and keep some. You have a garbage collector coming to your house to dispose of the unwanted items, but in order for him to differentiate between the objects that you want to keep and those that you want to discard, you mark the items that you want him to collect when he arrives. This is how the Garbage collector works. First it marks all of the unwanted objects and then it collects them all at once. The garbage collector runs frequently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.