This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
System.gc() does not guarantee that the finalize() method will run. It all depends upon the underlying JVM implementation. So, it may work in some computers and not in others. It also depends upon how much memory has been used up by the JVM. If very less memory is left, then garbage collection 'can' be started by the JVM itself.
Please point out if I am wrong.
Joined: Jun 21, 2006
How i will know that finalize block is executing because the "Going for GC" out put is not printing.
You cannot guarantee that the object will be garbage collected, if it is, then finalize() will be called. System.GC may or may not cause garbage collection, usually it does - but it is not certain. Sometimes it helps to call System.GC more than once - but you can never be certain that it has the effect you want.
By the way: the finalize() method in this code is public (it has been widened from protected access). If a subclass of this class wanted to use a protected finalize() method (as in Object's contract) it cannot do so.