Garbage Collections Questions
Practice Garbage Collections MCQs with answers and explanations. Page 1 of 1.
Category
Java Programming
Topic
Garbage Collections
Page
1 / 1
Mode
Practice
Questions
Open any question to view the answer and explanation.
Java garbage collection: At which program point is the Bar object created on line 6 eligible for collection?
class Bar { }
class Test
{
Bar doBar()
{
Bar b = new Bar(); // line 6
return b; // line 7
}
public static void main (String args[])
{
Test t = new Test(); // line 11
Bar newBar = t.doBar(); // line 12
System.out.println("newBar");
newBar = new Bar(); // line 14
System.out.println("finishing"); // line 15
}
}
Open
View answer
Java reachability: When is the B object (created on line 3) definitely eligible for garbage collection?
void start() {
A a = new A();
B b = new B(); // line 3
a.s(b);
b = null; // line 5
a = null; // line 6
System.out.println("start completed"); // line 7
}
Open
View answer
In Java memory management, who can actually destroy an object reference x?
Open
View answer
Java GC and parameter passing: When is the Demo object created in start() eligible for garbage collection?
class Test
{
private Demo d;
void start()
{
d = new Demo();
this.takeDemo(d); // line 7
} // line 8
void takeDemo(Demo demo)
{
demo = null;
demo = new Demo();
}
}
Open
View answer
After the assignment on line 8, how many X objects are eligible for garbage collection?
public class X
{
public static void main(String [] args)
{
X x = new X();
X x2 = m1(x); // line 6
X x4 = new X();
x2 = x4; // line 8
doComplexStuff();
}
static X m1(X mx)
{
mx = new X();
return mx;
}
}
Open
View answer
After line 11 executes, how many X2 objects are eligible for garbage collection (note the cyclic references)?
class X2
{
public X2 x;
public static void main(String [] args)
{
X2 x2 = new X2(); // line 6
X2 x3 = new X2(); // line 7
x2.x = x3;
x3.x = x2;
x2 = new X2();
x3 = x2; // line 11
doComplexStuff();
}
}
Open
View answer
In the following method, where is there the highest likelihood of the garbage collector being invoked (consider object reachability within methodA)?
class HappyGarbage01
{
public static void main(String args[])
{
HappyGarbage01 h = new HappyGarbage01();
h.methodA(); // line 6
}
Object methodA()
{
Object obj1 = new Object(); // line 9
Object[] obj2 = new Object[1]; // line 10
obj2[0] = obj1; // line 11
obj1 = null; // line 12
return obj2[0]; // line 13
}
}
Open
View answer
When does the Float object created on line 3 become eligible for garbage collection?
public Object m()
{
Object o = new Float(3.14F);
Object[] oa = new Object[1];
oa[0] = o; // line 5
o = null; // line 6
oa[0] = null; // line 7
return o; // line 8
}
Open
View answer
Practice smarter
Solve a few questions daily and revisit weak topics regularly to improve accuracy.