Java Challenge #3: Garbage Collector

Good challenge! How many objects will be eligible for the garbage collector after the executeAction() invocation?

Try to solve this challenge before seeing the answer below.

 public class GarbageCollectorTest {

    public static void main(String[] args) {
	HowManyObjectsWillBeCleanedByTheGarbageCollector gc = new GarbageCollectorTest()
		.new HowManyObjectsWillBeCleanedByTheGarbageCollector();


	System.out.println("How many objects are eligible be collected by "
		+ "the Garbage Collector after "
		+ "the executeAction() method invokation?" + gc);

    private class HowManyObjectsWillBeCleanedByTheGarbageCollector {
	private Character homer = new Character("Dooh");
	private Character misterBurns = new Character("you are fired");
	private Character bart = new Character("eat my shorts");
	private Character elBarto;

	public void executeAction() {;;
	    makeTwoCharactersTalk(misterBurns, homer);

	    misterBurns = null;

	    elBarto = bart;
	    bart = null;;

	private void makeTwoCharactersTalk(Character misterBurns, Character homer) {;;

	    misterBurns = null;
	    homer = null;

    // class Character omitted

class Character {
    private String talk;

    public Character(String talk) { = talk;

    public void talk() {

Answer: Only one object, misterBurns! When we invoke the makeTwoCharactersTalk we pass the objects by reference and not by value. This means the object is still in the Heap. We also pass the reference of bart to elBarto. When we pass null to bart, we still have the object of Bart into elBarto.

Java Challenge #3: Garbage Collector

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s