Wednesday 12 October 2016

Explain the use of finalize method with Example


 Explain the use of 

 finalize method with Example 




Finalize() Method:

  • When you will need to do some actions when an object is destroyed by garbage collection.
  • For example when your program is using some non-java resources, you have to free the memory for these resources.
  • This process is known as finalization.
  • The finalization is done by the finalize() method.


Syntax :

protected void finalize()
{
//statements to be executed
}

  • Finalize() method does not return any value so the return type is void.
  • The finalize() mehod is called just before when java runtime system perform garbage collection.
  • Finalize method is object class method, so applied all the class.
Example :

class Demo
{
static int cnt=0;
protected void finalize()
{
cnt++;
System.out.println
                ("Finalize"+ cnt);
}
public static void main(String[] a)
{
int i;
Demo obj[] = 
                new Demo[10000000];
for (i=0;i<10000000;i++)
{
obj[i]s=new Demo();
}
for (i=0;i<10000000;i++)
{
obj = null;
}
System.gc();
}
}



No comments:
Write comments

Labels

ADVERTISEMENT