0
0
Javaprogramming~15 mins

Garbage collection overview in Java

Choose your learning style8 modes available
menu_bookIntroduction
Garbage collection helps automatically clean up memory that your program no longer uses, so your computer doesn't run out of space.
When your program creates many objects and you want to avoid running out of memory.
When you want to prevent your program from crashing due to memory leaks.
When you want to focus on writing code without manually managing memory.
When your application runs for a long time and needs to free unused memory regularly.
regular_expressionSyntax
Java
No direct syntax to call garbage collection; it runs automatically.
You can suggest it by calling:
System.gc();
Garbage collection runs automatically in Java, so you usually don't need to call it yourself.
Calling System.gc() is only a suggestion to the JVM; it may or may not run immediately.
emoji_objectsExamples
line_end_arrow_notchThis line suggests to the Java Virtual Machine to perform garbage collection.
Java
System.gc();
line_end_arrow_notchObjects that are no longer referenced can be cleaned up automatically.
Java
// Create objects
String text = new String("Hello");
// After text is no longer used, garbage collector can free its memory
code_blocksSample Program
This program creates a String object, removes its reference, and suggests garbage collection. The output confirms the suggestion.
Java
public class GarbageCollectionDemo {
    public static void main(String[] args) {
        // Create an object
        String message = new String("Hello, world!");
        // Remove reference
        message = null;
        // Suggest garbage collection
        System.gc();
        System.out.println("Garbage collection suggested.");
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch
Garbage collection helps prevent memory leaks by freeing unused objects.
line_end_arrow_notch
You cannot predict exactly when garbage collection will run.
line_end_arrow_notch
Good programming practice is to remove references to objects you no longer need.
list_alt_checkSummary
Garbage collection automatically frees memory of unused objects.
You can suggest garbage collection with System.gc(), but it is not guaranteed to run immediately.
It helps keep your program running smoothly without manual memory management.