What is garbage collection in Java?
In Java you create objects with new but you never delete them. The garbage collector of the JVM finds the objects that no variable can reach anymore, and frees their memory.
public class Main {
public static void main(String[] args) {
Object o = new Object();
o = null; // now nothing points to the first object
System.gc(); // only a request; the JVM decides
System.out.println("Done");
}
}
Output
Done
- You can not force garbage collection.
System.gc()is only a hint. - Memory leaks can still happen, for example when a static list keeps growing.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |