Home > Java > javaTutorial > body text

Destructor in Java

WBOY
Release: 2024-08-30 15:26:43
Original
1117 people have browsed it

Destructors in Java can be learned with the finalize method in Java. The concept is as same as the finalize method. Java works for all except the destructor with the help of the Garbage collection. Therefore, if there is a need for calling the destructor, it can be done with the help of the finalize method. This method is not independent as it relies on Garbage Collection. The garbage collector is a thread that deletes or destroyed the unused object in the heap area. Say if the object is connected to a file or say some database application or network connections, before deleting or destroying the object, it has to close all the connections related to these resources before the garbage collection takes place. This closing of the functions is done by calling the finalize method.

Definition of Destructor in Java

“ Destructor is a method called when the destruction of an object takes place. “ The main goal of the destructor is to free up the allocated memory and also to clean up resources like the closing of open files, closing of database connections, closing network resources, etc.,

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Syntax

class Object
{
protected void finalize()
{
//statements like the closure of database connection
}
}
Copy after login

How Does Destructor Work in Java?

The destructor has a finalize() method in java, which is similar to the destructor in C++. When the objects are created, they are stored in the heap memory. These are accessible by main or child threads. So when these objects are no more used by the main thread or its child threads, they become eligible for garbage collection and the memory which was acquired now becomes available by new objects being created. Before an object is a garbage collected by the garbage collector, the JRE (Java Runtime Environment) calls the finalize() method to close the input-output streams, the database connections, network connections, etc. Note that the finalize method called is protected. Why finalize is protected because it can be either called by the base class or derived class? finalize method is present in the Object class. Thus in case you want to call this finalize method from other objects, you can change this protected to public.

Syntax:

protected void finalize throws Throwable()
{
//Keep some resource closing operations here
}
Copy after login

Methods of finalize()

  1. finalize() method is protected as defined in java.lang.Object class.
  2. finalize() method is called only once.
  3. to override the finalize() method, you need to call the finalize method explicitly.
  4. GC() is a service of JVM to execute Garbage Collection; it is called when the heap memory is full and needs memory for new arriving objects.
  5. JVM ignores all exceptions except the unchecked exceptions that occur in the finalize method.

Example #1

The String class corresponding finalizes method is called instead of the finalize method present in the program in the below program. The finalize method is overridden here.

Code:

public class Demo
{
public static void main(String[] args)
{
Integer i = new Integer(2);
i = null;
System.gc();
System.out.println("In the Main Method");
}
protected void finalize()
{
System.out.println("object is garbage collected ");
}
}
Copy after login

Output:

Destructor in Java

Example #2

In the below program, the finalize method is called internally; no explicit call required.

Code

public class Demo
{
public static void main(String[] args)
{
Demo dm = new Demo();
dm = null;
System.gc();
System.out.println("In the Main Method");
}
protected void finalize()
{
System.out.println("object is garbage collected ");
}
}
Copy after login

Output:

Destructor in Java

Example #3

In the below program, the finalize was called internally depending upon the number of objects created.

Code

public class NewProgram{
public void finalize(){
System.out.println("object is garbage collected");
}
public static void main(String args[]){
NewProgram np1=new NewProgram(); //first instantiation of Class NewProgram
NewProgram np2=new NewProgram(); //second instantiation of Class NewProgram
np1=null;
np2=null;
System.gc();
System.out.println("In the Main Method");
}
}
Copy after login

Output:

Destructor in Java

Example #4

In the below program, two objects are created the finalize is called once as both the objects are pointing to the same.

Code:

public class NewProgram{
public void finalize(){
System.out.println("garbage collected");
}
public static void main(String args[]){
NewProgram np1=new NewProgram(); //first instantiation of Class NewProgram
NewProgram np2=new NewProgram(); //second instantiation of Class NewProgram
np1 = np2; // both now pointing to same object
System.gc();
System.out.println("in the Main Method");
}
}
Copy after login

Output:

Destructor in Java

Example #5

In the below program, the finalize method will be called twice explicitly and internally both.

Code

public class Demo
{
public static void main(String[] args)
{
Demo dm = new Demo();
dm.finalize();
dm = null;
System.gc();
System.out.println("In the Main Method");
}
protected void finalize()
{
System.out.println("garbage collected ");
}
}
Copy after login

Output:

Destructor in Java

Example #6

In the below program, an arithmetic exception is called in the finalize method as it is explicitly called, which further causes the exception and stops the execution of the remaining program.

Code:

public class Demo
{
public static void main(String[] args)
{
Demo dm = new Demo();
dm.finalize();
dm = null;
System.gc();
System.out.println("In the Main Method");
}
protected void finalize()
{
System.out.println("garbage collected ");
System.out.println(10 / 0);
}
}
Copy after login

Output:

Destructor in Java

Example #7

There is no exception called in the below program as it is not called explicitly and continues the execution of the remaining program.

Code:

public class Demo
{
public static void main(String[] args)
{
Demo dm = new Demo();
dm = null;
System.gc();
System.out.println("In the Main Method");
}
protected void finalize()
{
System.out.println("garbage collected ");
System.out.println(10 / 0);
}
}
Copy after login

Output:

Destructor in Java

Advantages of Destructor in Java

  1. The destructor destroys the value created by the constructor to space in heap memory.
  2. Destructor is always called at the end of the program.
  3. Destructor is never overloaded destructor doesn’t take any argument.
  4. No need to define our constructor; the compiler creates for us one.

Conclusion

I hope this article was interesting and informative both for you to learn the topic. This article given has covered almost all the topics you are looking for, and I hope fulfills all of your requirements.

The above is the detailed content of Destructor in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!