Most asked top Interview Questions and Answers | Online Test | Mock Test
Education platform for interview prep, online tests, tutorials, and live practice

Build skills with focused learning paths, mock tests, and interview-ready content.

WithoutBook brings subject-wise interview questions, online practice tests, tutorials, and comparison guides into one responsive learning workspace.

Search the library
Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: How can you force garbage collection?
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

The following code of program will help you in forcing the garbage collection. First of all we have created an object for the garbage collector to perform some operation. Then we have used the System.gc(); method to force the garbage collection on that object. Then we have used the System.currentTimeMillis(); method to show the time take by the garbage collector.


import java.util.Vector;

public class GarbageCollector{
	public static void main(String[] args) {
		int SIZE = 200;
		StringBuffer s;
		for (int i = 0; i < SIZE; i++) {
		}
		System.out.println("Garbage Collection started explicitly.");
		long time = System.currentTimeMillis();
		System.gc();
		System.out.println("It took " +(System.currentTimeMillis()-time) + " ms");
	}
}

Save For Revision

Bookmark this item, mark it difficult, or place it in a revision set.

Open My Learning Library
Is it helpful? Yes No

Most helpful rated by users:

©2026 WithoutBook