Consider the following Java code snippet. What will be printed when it runs?
public class Test { public static void main(String[] args) { Test obj = new Test(); obj = null; System.gc(); System.out.println("End of main"); } protected void finalize() throws Throwable { System.out.println("Finalize called"); } }
Garbage collection in Java is not guaranteed to run immediately after System.gc().
The finalize() method may not be called immediately or at all before the program ends. The output will always print "End of main". "Finalize called" is not guaranteed.
What will be printed by this Java program?
public class Demo { static int count = 0; Demo() { count++; } public static void main(String[] args) { Demo a = new Demo(); Demo b = new Demo(); a = null; System.gc(); System.out.println(count); } }
Count increments on each object creation, not on garbage collection.
Two objects are created, so count is 2. Nullifying a and calling System.gc() does not reduce count.
What error will this code produce when compiled or run?
public class Sample { public void finalize() throws Throwable { System.out.println("Cleaning up"); } public static void main(String[] args) { Sample s = new Sample(); s = null; System.gc(); } }
Check the signature of the finalize() method in Java.
The finalize() method is deprecated but still valid with this signature. It may not be called before program ends, so no output is guaranteed.
Choose the correct method signature to override finalize() in Java.
The finalize() method must have a specific signature to override properly.
The correct signature is protected void finalize() throws Throwable. Other options have wrong access modifiers or exception types.
Given the following Java code, how many objects are eligible for garbage collection after the last line executes?
public class Node { Node next; public static void main(String[] args) { Node a = new Node(); Node b = new Node(); Node c = new Node(); a.next = b; b.next = c; c.next = a; a = null; b = null; } }
Consider the references and the circular links between objects.
Even though a and b are set to null, the three Node objects reference each other in a cycle, so none are eligible for garbage collection.