How do you use memory leaks in Java with a simple code example?

Memory leaks in Java occur when the program holds references to objects that are no longer needed, preventing the garbage collector from reclaiming their memory. This can lead to increased memory usage and potential application crashes over time.

Below is a simple example demonstrating how a memory leak can happen in Java:


import java.util.ArrayList;
import java.util.List;

public class MemoryLeakExample {
    // A list that will hold references to objects
    private static List myList = new ArrayList<>();

    public static void main(String[] args) {
        for (int i = 0; i < 100000; i++) {
            // Creating a new String object and adding it to the list
            String str = new String("This is a memory leak example: " + i);
            myList.add(str);
        }
        
        System.out.println("Memory leak created, check memory usage.");
        // At this point, myList holds references to many String objects,
        // preventing them from being garbage collected.
    }
}
        

Java Memory Leak Garbage Collection Memory Management Software Development