Reputation: 26067
Might be silly question,
Need understanding on below
1.) // reference declared , null Object
String message = null;
in above case, when will the reference 'message' eligible for garbage collection
, read somewhere if make string reference to null
it becomes eligible for GC
2.) // reference declared , empty String Object
String message = "";
3.) // reference declared , Object with value Hello
String message = "Hello";
From above, 1 references is created
in all the three cases,
What about the Object creation
..?? How will they be maintained in String Pool
and heap
Upvotes: 1
Views: 953
Reputation: 298898
in above case, when will the reference 'message' eligible for garbage collection, read somewhere if make string reference to null it becomes eligible for GC
It's not a reference. It's a local variable which could (but doesn't) contain a reference. If this variable was assigned to a non-constant String, that reference would eventually be eligible for garbage collection, once the variable is no longer referenced.
As it is though, the variable points to null, and will just vanish once the declaration scope (usually a method) is left. Nothing to garbage collect here. Garbage collection is about objects, not variables.
Upvotes: 1
Reputation: 1902
First of all, references are not GCed Objects are. But with Strings its a bit tricky as Strings obejcts and String literals are different.
String s = "Hello";
String s1 = new String("Hello");
These are different. First one creates a String literal which goes into pool and a reference s is attached to it. Second one creates an Object of type String which points to the String literal "Hello" in pool and the reference s1 is attached tot he String object and not to the literal.
In general when an object (think as a generic object lets say Employee) is not in the live path of thread or execution flow and is not being referred by any other objects (referred doesnot mean a reference here but an association between objects like Employee and Address) it becomes eligible for GC.
Null is a special type in Java which is not subjected to GC general GC rules. Any reference not pointing to an object location is actually pointing to null.
Upvotes: 2
Reputation: 37023
1.) No object created. It's just reference you have defined.
2.) String object (referring to empty string "") created in string pool.
3.) String object (referring to "Hello") created in string pool.
Upvotes: 0