Are primitive types garbage collected? Well, yes and no. Let's take an "int" and see what happens.
If our "int" is a member variable of a class, it's easy. An instance of the class will ultimately be garbage collected, and the "int" will go with it.
But what about local variables? Eg,
These are not garbage collected. Instead, they are allocated on the
stack. When the
thread enters the method, the JVM allocates a
stack frame with enough space for all local variables and some administrative stuff besides. This stack frame is deallocated the moment you leave the method (whether it's with a return, by throwing an exception or by encountering the closing brace). Memory management is directly tied to the foo() method block and completely automatic (they are called
automatic variables in C/C++ parlance).
What about an object, then?
You might wonder, is this automatically allocated and deallocated too? Well, no. There are actually
two allocations here. First, a
reference variable holding a reference to a Bar object is allocated on the stack. It will be deallocated along with the rest of the stack frame as soon as you leave the foo() method. Second, a
Bar object which is allocated on the heap. A reference to this object is assigned to the "bar" variable. The object will ultimately be garbage collected.
Then your final question.
String literals take a rather privileged position in Java. There is only ever one copy of each literal:
These literals are
not subject to garbage collection. They are part of a "string pool" that stays around as long as your application lives. You add new strings to the pool, or retrieve existing instances, using the intern() method:
Hope this helps
- Peter