What does Finalize() method in Java do?

I know that the final keyword can be used for classes, methods and for variables. And If I am not wrong the final class can not be subclassed and the final method can not be overridden and the fianl variable can not be changed from its initialized value. What exactly Finalize() method in a Java program do? When can we use that method? Can someone please explain with an example program?

Replies

  • monujatt
    monujatt
    Finalize() method is basically used for the garbage collection (for releasing resources like opened files etc.)
    class TestFile {
    FileInputStream aFile = null;
    TestFile(String filename) {
    try {
    aFile = new FileInputStream(filename);
    } catch (java.io.FileNotFoundException e) {
    System.err.println("Could not open file " + filename);
    }
    }
    }

    protected void finalize () throws throwable {
    if (aFile != null) {
    aFile.close();
    aFile = null;
    }
    }
  • sulochana anand
    sulochana anand
    It can be used when an object is about to destroy bu need to perform some action.there might be some situation where an object holding non java resouce such as file handler or charecter font etc and a programar want to make sure these resouces are freed before an object is destroyed.in such situation java provide us a method finalize().by using this we can define an action that is about to occur when an object is about to regaind by garbage collector.

You are reading an archived discussion.

Related Posts

Hi All! This is such an amazing thread. Feel free to visit my site to learn about coal statistics and coking coal index.
Happy Diwali to all CEans! To the Tamil CEans: எல்லோருக்கும் என் உளமார்ந்த தீபாவளி நல் வாத்துக்கள்
Why do the file size of different photos taken from the same camera differ.? What all factors affect the size.?
Remember Er. Narayanan Menon? The engineer who entered Limca Book Of Records by using simple techniques to suck the maximum mileage out of his Tata Indigo Manza Qudarajet! Mr. Menon...
Magna Parva engineers develop ultrasonic space drill | In-depth | The Engineer