Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection

 
Mohan Chandrasekaran
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is related to making a reference to null for String object

Say we have the following code:

1.String s1 = "SCJP1.4"
2.String s2 = "SCWCD1.4"
3.s1 = null;
4.s1 = "SCJP1.4";

Here when we make the reference s1 to null, whether the String object referenced by the literal namely "SCJP1.4" is eligible for garbage collection.

I read like literal itself a reference to String object and that when you try to assign the literal to String reference,the reference will be pointing to String object. So when s1 is made null. The literal referring to String object will be exisiting.
 
vipul patel
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thumb rule in java: whenever any object is unreachable it is eligible for garbage collection.

1.String s1 = "SCJP1.4"
2.String s2 = "SCWCD1.4"
3.s1 = null;
4.s1 = "SCJP1.4";

In this case, s2 is eligible for garbage collection after line 4 is executed. this is because String object (in the string pool) with value "SCWCD1.4" is unreachable.

But s1 not. since it is reused at line 4. object "SCJP1.4" at line 4 is basically same as line 1. since string literals are always taken from the string pool.
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In this case, s2 is eligible for garbage collection after line 4 is executed. this is because String object (in the string pool) with value "SCWCD1.4" is unreachable


This is what I feel , Objects in the String Pool will not be GC'd.
also in the above case s2 is not at all set to null. So none of the objects will be eligibe for GC
[ December 19, 2005: Message edited by: Srinivasa Raghavan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic