Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use finalize() method in java with example
3716 Views
GC (Garbage Collector) calls finalize() when an object at end of scope. Finalize() can be overridden by subclasses to do some other process related cleanup.
Finalize Method Example in JAVA
class Students {
    int rno;
    String student_name;
    
    public Students(int rno,String student_name) {
        this.rno = rno;
        this.student_name = student_name;
    }
    
    public void display(){
        System.out.println("RNo :"+rno);
        System.out.println("Name :"+student_name);
    }
    
    @Override
    public void finalize() throws Throwable{
        System.out.println("Object going to destroy... ["+rno+","+student_name+"]");
        super.finalize();
    }
}

class Solution {
    public static void main(String args[])throws Exception{
        Students stu = new Students(1001,"Sarathy");
        stu.display();
        
        // Tells to JVM for running finalize() method at exit
        Runtime.runFinalizersOnExit(true);
    }
}
Output 
RNo :1001
Name :Sarathy
Object going to destroy... [1001,Sarathy]
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details