×

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an idea of how it works.

Java Constructors

Constructor is a special type of method. And this method is used for initializing the objects. When we create an object for the class, this constructor will be automatically called. Method and constructors are similar. A constructor can also define as a block of codes which is directly called when the object is created for the class. Creating the object for the class is also called an instance of class creation. At least one constructor is called when we create an object to the class using the new () keyword.

Another thing is in the Java compiler, and there will be a default constructor. This Java compiler only creates this default constructor. This default Java constructor does not have any parameters. In the simplified version, we can say that if in a Java program there is no constructor in a class, the default constructor will be created.

Let's understand this Java constructor concept by creating a class and by creating a default constructor by taking simple example code.

 // A simple Java program for understanding the concept of the Creation of object default constructor
Class Java
{
……….
//Creation of constructor
New Java () {
…………..
           }
 // The below line of code gives the explanation of how we create an object for the above class. And the below line of code will call the above-created constructor automatically. 
Java object = new Java ();

 Let us look at a simple Java program about how the constructor works to understand it more clearly.

//Class name is Student
class Student{ 
    int ID;  
    String student_name; 
    //Creating constructor by passing parameters
    Student(int n,String N){  
    ID = n;  
    student_name = N;  
    }  
    //Display the ID's and Names of the students
    void display_info(){System.out.println("The student id is:"+ID);
        System. out.println("Name of the student is:"+student_name);
    }  
   
    public static void main(String args[]){  
    //Creating instances for class by passing the values  
    Student s = new Student(111,"Isha");  
    Student s = new Student(222,"Krishnan");  
    //Calling method to display for displaying the values 
    S.display_info();  
    s.display_info();  
   }  
}   

 Output:

Java Destructors

In the above, we can understand how the constructor is called and how the parameters will be passed.

Java Destructor

The method which is automatically called when the object is no longer needed is known as “Destructor”. Destructor is a special method. Java destructors are non-deterministic. These destructors are also called finalizers. The garbage collector in Java handles the allocation and deallocation of objects.

The object occupies space in the memory when we create an object of the class. And this memory will be deallocated by the destructor. In Java, there is a garbage collector that does the same work which is done by the destructor. Usually, objects occupy unnecessary space if the memory occupied by them does not get deleted. So, to delete this memory and overcome this problem, we use destructors. The garbage collector deletes the object when the object completes its life cycle and releases the memory that is occupied by the object.

Destructor and finalize () methods do the same job. Constructor and destructor both works in the opposite way. Simply, we can say the constructor is the opposite of the destructor. If the constructor is used to initialize the objects, then destructors release the memory occupied by the object.

Syntax for finalize () method:

Protected void finalize throws Throwable ()
{
// resources to be close
}

The thing and the point to understand is the finalize () method is not a destructor but works similar to a destructor.

Java provides a garbage collector. This garbage collector works similar to a destructor. Actually, the thing is, there is no concept of destructors in this Java programming language.

Let's see an example to understand the concept of destructors.

Destructor.java

public class Destructor  
{  
public static void main(String[] args)  
{  
Destructor d= new Destructor ();  
d.finalize();  
d = null;  
System.gc();  
System.out.println("In the main method");  
}  
protected void finalize()  
{  
System.out.println("Garbage collector destroys the object.");  
}  
}   

Output:

Java Destructors

Advantages of Destructor

  • The resources will be released from occupied by the object.
  • Destructor is automatically invoked at the end of the program execution. That is the reason no explicit call is required.
  • The destructor cannot be overloaded.

Related Topics

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.