• Post Reply Bookmark Topic Watch Topic
  • New Topic

Garbage Collection  RSS feed

 
kumar bangali
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Consider the following question from JQ+
Which is the earliest line in the following code after which the object created on the //1 can be garbage collected, assuming no compiler optimizations are done?
public class NewClass
{
static String enterTheDragon()
{
String a = new String("hello");
String b = new String("world !"); // 1
String c = new String(a + b + ""); // 2
String d = b; // 3
b = a; // 4
d = a; // 5
return c; // 6
}
public static void main(String args[])
{
String s = enterTheDragon(); // 7
System.out.println(s); // 8
}
}
The answer given is line 5. Is this correct? Should we not point the object to a null reference before it becomes eligible for garbage collection?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The point is that the reference to the object created in line //1 and held in variable b and variable d (due to line //3) is lost when another reference is placed in b and d.
After line 5 executes, there is no longer any reference to the object anywhere in the program so it is eligible for GC.
Bill
 
Rick Salsa
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi William,
Are these kinds of questions asked on the exam?
/rick
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a String is created, a chunk of memory is set aside and initialized with the contents of the String, in this case "world." The name of the String actually holds the address where the literal resides and points at it. After line 5, no variable references(points at) "world" anymore and thus it becomes fodder for the GC.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Are these kinds of questions asked on the exam?"
You bet they are. Understanding GC is essential.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!