×

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

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.