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 |
|---|
| Java Date and Time (java.time) |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| What is garbage collection in Java? |
| What is the difference between stack and heap memory in Java? |
| What are annotations in Java? |
| What is reflection in Java? |