What method in Java is used to destroy your objects [closed]
Can you give me one example for my question?
Sorry, but there isn't really a "free" or "dispose" equivalent in Java.
The best you can do is just set the object to null (removes the reference). Then explicitly tell the garbage collector you're going rambo (its somewhere in java.lang.Runtime
).
The memory occupied by Java objects that are no longer accessible may be reclaimed by the virtual machine's garbage collector. As other have noted, this is automatic. In contrast, the normal operation of a program may allocate certain system resources that must be freed explicitly. Native screen resources are an example. A partial list of such methods inlcudes these:
java.awt.Component.BltBufferStrategy#dispose() java.awt.Component.FlipBufferStrategy#dispose() java.awt.CompositeContext#dispose() java.awt.Graphics#dispose() java.awt.im.InputContext#dispose() java.awt.im.spi.InputMethod#dispose() java.awt.image.BufferStrategy#dispose() java.awt.Image#flush() java.awt.PaintContext#dispose() java.awt.Window#dispose() java.io.InputStream#close()* java.io.OutputStream#close()* java.sql.Connection#close() java.util.Timer#cancel() javax.imageio.ImageReader#dispose() javax.imageio.ImageWriter#dispose() javax.print.StreamPrintService#dispose() javax.security.sasl.SaslClient#dispose() javax.security.sasl.SaslServer#dispose() javax.swing.DebugGraphics#dispose() javax.swing.JInternalFrame#dispose() org.ietf.jgss.GSSContext#dispose() org.ietf.jgss.GSSCredential#dispose() * Includes subclasses
There is not a method per se. The finalize()
method, defined in the top-level Object
, may be invoked when the object is deallocated by the garbage collector, but this is not a behavior you can rely upon.