Table of Contents
How Does Destructor Work in Java?
Example #7
Advantages of Destructor in Java
Conclusion
Home Java javaTutorial Destructor in Java

Destructor in Java

Aug 30, 2024 pm 03:26 PM
java

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles