The Java Virtual Machine (JVM) actively and automatically manages the memory your application uses. Some things to keep in mind about Java's memory management:
Memory is automatically allocated in heap memory for objects that your program creates.
When an object can no longer be accessed by your program (usually by falling out of scope so that no variables that reference the object can be accessed) the memory is automatically reclaimed by a process called garbage collection.
Garbage collection is automatic and non-deterministic. Your program can't know (or predict) when garbage collection is going to occur (so you don't know exactly when unreachable objects will be reclaimed).
In the majority of cases, the JVM manages memory so well that no memory leaks occur even when a program runs for a long time (and creates and reclaims many objects).
By the above reasoning, the code snippet you show will not result in any memory leaks. There are only a few situations in which memory leaks will occur in Java:
1. When you do your own memory management. Memory leaks can occur if you implement your own data structures for objects. For example, if you create your own stack implementation, objects that are "popped" out of your stack can still have active references to them. When this happens, the object will not be garbage collected even if it is no longer in the active portion of your stack. This is one of the few cases in which it can be important to actively assign null
to elements that may refer to objects that are no longer "being used."
2. Any time you have a long-lived object that holds a reference to an object that you intend to be short lived. The most common situation in which this can cause memory leaks is in the use of non-static inner classes and anonymous classes (both of which contain a reference to their enclosing instance).
Every non-static Inner Class has an implicit reference to its surrounding class. Anonymous Classes are similar. To successfully create a memory leak simply pass an Inner Class object to a method which keeps references to the provided objects and you're done.
Why does this cause a memory leak? Suppose you implement something like a cache. Next follow the execution path to a local object which stores some of its inner class objects into the cache. After the local object was out of scope, it won't be garbage collected anymore! The inner class object in the cache holds a reference to the surrounding object and that one is still referenceable and therefore not a candidate for garbage collection anymore. The same is true for anonymous classes!