How to deallocate memory for objects that are no longer needed ?

When you need deallocate memory that is allocated by some objects, but in this time unused, you can use this code. The code call explicitly Garbage Collector manager:

/* -- create some instances in memory */
for ( int i = 0; i < 10000; i++ ) { JButton button = new JButton(); }
/* -- check free memory in heap memory */
System.out.println( Runtime.getRuntime().freeMemory() );

System.out.println( Runtime.getRuntime().freeMemory() );

The output could be (in this case is value of new free memory greater):


You can call System.gc() too. There are no difference between Runtime.getRuntime().gc() and System.gc() -> because System.gc() is calling Runtime.getRuntime().gc().