The developer should not take care of freeing memory. Instead, the automated Garbage Collector (GC) handles it.
The GC is a process which runs at near idle state of the application, or when the sources are low. This is due to optimization where the weight is on the fast and effective application executing.
Exception are particular objects which have .close methods. Invoking them after processing releases memory allocation.
The GC can empty a memory location in case no reference points on it.
Can not free memory allocation in case the object behind the reference still exists.
EXAMPLE FOR CREATING REFERENCING:
Collection and StringBuilder objects handle dynamic memory allocation. Because of this, they occupy more than the actually needed in order to cover instant data grow.
They can have methods to define they allocated space (element number) upon construction, or trim the empty memory parts for the case using such method is a must.
Scanner object keeps memory allocation until .close() method is called.
The GC can be forced to run.
EXAMPLE FOR FORCING THE GARBAGE COLLECTOR RUNNING: