Avatar ·

How to create a memory leak in Java? Code examples and explanation

Hello everyone! I'm a beginner Java developer and I'm very interested in the topic of memory management. I know that Java has a Garbage Collector that automatically frees memory from objects that have no references. But I've been told that even in Java, you can create a memory leak if you write code carelessly. I'm trying to understand exactly how this happens. I wrote a simple example, but I'm not sure if it's correct. Here's the code: ```java import java.util.ArrayList; import java.util.List; public class MemoryLeakExample { private static List list = new ArrayList<>(); public static void main(String[] args) { while (true) { list.add(new Object()); } } } ``` This code will obviously cause an OutOfMemoryError because we're infinitely