How can you ensure that the memory allocated by an object is freed?

  1. By invoking the free method on the object

  2. By calling system.gc() method

  3. By setting all references to the object to new values (say null).

  4. Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object.


Correct Option: D
Explanation:

The correct answer is D. Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object. The JVM will automatically free the memory used by an object when it is no longer referenced by any other object.

Option A is incorrect because there is no free method in Java.

Option B is incorrect because calling system.gc() only requests the JVM to run the garbage collector, but it does not guarantee that the garbage collector will actually free the memory used by the object.

Option C is incorrect because setting all references to the object to new values (say null) will only prevent the JVM from garbage collecting the object, but it will not actually free the memory used by the object.

The memory used by an object will only be freed when the object is no longer referenced by any other object. This is the principle of garbage collection.

Find more quizzes: