SlideShare a Scribd company logo
Destructor in Java
CONTENT
• DESTRUCTOR
• WORKING OF DESTRUCTORS
• NEED FOR DESTRUCTORS
• OBJECT DESTRUCTION IN JAVA
• WAYS TO HANDLE CLEANUP IN JAVA
• GARBAGE COLLECTION IN JAVA
• ADVANTAGES OF DESTRUCTORS
• HOW DESTRUCTOR WORKS
• FINALIZE() METHOD (DEPRECATED)
• BEST PRACTICES FOR RESOURCE CLEANUP
• CONCLUSION
DESTRUCTOR
• A destructor is a special method that is automatically
invoked when an object is no longer needed, mainly used
to free resources like memory, database connections, or
file handlers.
• Java does not have explicit destructors because
Java automatically manages memory using Garbage
Collection (GC).
How does destructor work?
• When the object is created it occupies the space in the heap.
These objects are used by the threads. If the objects are no
longer is used by the thread it becomes eligible for the
garbage collection. The memory occupied by that object is
now available for new objects that are being created. It is
noted that when the garbage collector destroys the object,
the JRE calls the finalize() method to close the connections
such as database and network connection.
Why is a Destructor Needed?
• A destructor is typically needed to:
1.Release memory occupied by unused objects.
2.Close files, database connections, or network sockets to
prevent resource leaks.
3.Free system resources, such as locks or UI components.
How Does Java Handle Object Destruction?
• Java does not have explicit destructors because it has Garbage
Collection (GC), which automatically deallocates unused objects.
• Garbage Collection is not predictable. The JVM decides when to run
the Garbage Collector, meaning objects are not destroyed immediately
after they become unreachable.
• Java’s garbage collector automatically manages the
lifecycle of objects.
• When no references point to an object, it becomes eligible
for garbage collection.
• The garbage collector reclaims memory at its discretion,
making memory management automated and simplifying
development.
How to Handle Cleanup in Java?
• Since Java does not have destructors, it provides alternative mechanisms for
cleanup:
1.Garbage Collection (Automatic)
2.finalize() method (Deprecated after Java 9) The Java compiler shows warnings if
you use it.
3.try-with-resources (Best Practice)
4.Explicit close() methods (Manual Cleanup)
Garbage Collection in Java
• What is Garbage Collection?
• Garbage Collection is an automatic memory management feature
in Java.
• It reclaims memory by destroying objects that are no longer in use.
• The JVM decides when to run the garbage collector, making it non-
deterministic.
• Advantages:
• Reduces the risk of memory leaks.
• Simplifies memory management for developers.
Advantages of Destructors
• Automatic Resource Management: By automating the process of freeing
up memory and other resources, Java's garbage collector lowers the
possibility of memory leaks and improper resource management.
• Simplifies Programming: By eliminating the need for developers to
manually monitor and release memory, programming becomes simpler
and less prone to error.
• Enhances Performance: By effectively handling memory allocation and
deallocation, automated memory management can aid in performance
optimization.
Java finalize() Method
• Java provides an alternative way to do the same.
• The Java Object class provides the finalize() method that
works the same as the destructor. The syntax of the finalize()
method is as follows:
• Before Java 9, Java allowed the use of the finalize() method
to define cleanup tasks before the object is garbage
collected.
Finalize() Method (Deprecated)
• Java finalize() Method
• The finalize() method was used to perform cleanup tasks before an object was garbage collected.
• Syntax:
• java
• Copy
• protected void finalize() throws Throwable
• {
• // Cleanup code
• }
• Deprecated after Java 9: Due to its unreliable execution and performance overhead.
• Alternative: Use try-with-resources or explicit close() methods for resource cleanup.
Best Practices for Resource Cleanup
• Best Practices for Handling Cleanup in Java:
1.Use try-with-resources: Automatically closes resources like files, sockets, and database
connections.
2.java
try (FileInputStream fis = new FileInputStream("file.txt"))
{
// Use the resource
}
catch (IOException e)
{ e.printStackTrace();
}
2. Implement AutoCloseable: Create custom resources that can be used with try-with-
resources.
3. Avoid finalize(): Use explicit cleanup methods instead.
Conclusion
• Key Takeaways:
• Java does not have explicit destructors but uses Garbage
Collection for automatic memory management.
• The finalize() method is deprecated; use try-with-
resources or close() methods for cleanup.
• Automatic memory management simplifies programming
and reduces the risk of memory leaks.
• Always follow best practices for resource cleanup to ensure
efficient and reliable code.

More Related Content

PPTX
Constructors_this keyword_garbage.pptx
PDF
Garbage Collection in Java.pdf
PPTX
Garbage collection
PDF
Java Interview.pdf
PPTX
Constructor destructor.ppt
PPTX
Thread in java.pptx
PPTX
02D-Memory Management in Java.pptx
PPTX
Garbagecollectionhgfhgfhgfhgfgkfkjfkjkjfkjfjhfg.pptx
Constructors_this keyword_garbage.pptx
Garbage Collection in Java.pdf
Garbage collection
Java Interview.pdf
Constructor destructor.ppt
Thread in java.pptx
02D-Memory Management in Java.pptx
Garbagecollectionhgfhgfhgfhgfgkfkjfkjkjfkjfjhfg.pptx

Similar to DESTRUCTORS in Java for a lecture to understand (20)

PPTX
Java garbage collector JVM Garbage collection by Jeetendra Mandal
PPTX
More topics on Java
PPTX
object oriented programming using java, second sem BCA,UoM
PDF
Finalizers –The not so Good, the Bad and the Ugly
PPTX
Memory Management & Garbage Collection
PPTX
Object oriented programming in java
PPTX
Java GC
ODP
Java Garbage Collection, Monitoring, and Tuning
PDF
201801 CSE240 Lecture 13
PDF
Resource management in java bof6823 - java one 2012
PPTX
Unit No 2 Objects and Classes.pptx
DOCX
Viva file
PPTX
Destructors
PDF
Java - Basic Concepts
PPTX
Object orientation
PPTX
Module 10 : creating and destroying objects
PDF
Memory Heap Analysis with AppDynamics - AppSphere16
PPTX
Java Programming Comprehensive Guide.pptx
PDF
Garbage collection
Java garbage collector JVM Garbage collection by Jeetendra Mandal
More topics on Java
object oriented programming using java, second sem BCA,UoM
Finalizers –The not so Good, the Bad and the Ugly
Memory Management & Garbage Collection
Object oriented programming in java
Java GC
Java Garbage Collection, Monitoring, and Tuning
201801 CSE240 Lecture 13
Resource management in java bof6823 - java one 2012
Unit No 2 Objects and Classes.pptx
Viva file
Destructors
Java - Basic Concepts
Object orientation
Module 10 : creating and destroying objects
Memory Heap Analysis with AppDynamics - AppSphere16
Java Programming Comprehensive Guide.pptx
Garbage collection
Ad

Recently uploaded (20)

PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PPT
introduction to datamining and warehousing
PPTX
Nature of X-rays, X- Ray Equipment, Fluoroscopy
PPTX
communication and presentation skills 01
PPT
Occupational Health and Safety Management System
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Abrasive, erosive and cavitation wear.pdf
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PDF
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPT
Total quality management ppt for engineering students
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
introduction to datamining and warehousing
Nature of X-rays, X- Ray Equipment, Fluoroscopy
communication and presentation skills 01
Occupational Health and Safety Management System
R24 SURVEYING LAB MANUAL for civil enggi
Fundamentals of Mechanical Engineering.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Abrasive, erosive and cavitation wear.pdf
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Exploratory_Data_Analysis_Fundamentals.pdf
Fundamentals of safety and accident prevention -final (1).pptx
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
Visual Aids for Exploratory Data Analysis.pdf
Categorization of Factors Affecting Classification Algorithms Selection
Total quality management ppt for engineering students
Ad

DESTRUCTORS in Java for a lecture to understand

  • 2. CONTENT • DESTRUCTOR • WORKING OF DESTRUCTORS • NEED FOR DESTRUCTORS • OBJECT DESTRUCTION IN JAVA • WAYS TO HANDLE CLEANUP IN JAVA • GARBAGE COLLECTION IN JAVA • ADVANTAGES OF DESTRUCTORS • HOW DESTRUCTOR WORKS • FINALIZE() METHOD (DEPRECATED) • BEST PRACTICES FOR RESOURCE CLEANUP • CONCLUSION
  • 3. DESTRUCTOR • A destructor is a special method that is automatically invoked when an object is no longer needed, mainly used to free resources like memory, database connections, or file handlers. • Java does not have explicit destructors because Java automatically manages memory using Garbage Collection (GC).
  • 4. How does destructor work? • When the object is created it occupies the space in the heap. These objects are used by the threads. If the objects are no longer is used by the thread it becomes eligible for the garbage collection. The memory occupied by that object is now available for new objects that are being created. It is noted that when the garbage collector destroys the object, the JRE calls the finalize() method to close the connections such as database and network connection.
  • 5. Why is a Destructor Needed? • A destructor is typically needed to: 1.Release memory occupied by unused objects. 2.Close files, database connections, or network sockets to prevent resource leaks. 3.Free system resources, such as locks or UI components.
  • 6. How Does Java Handle Object Destruction? • Java does not have explicit destructors because it has Garbage Collection (GC), which automatically deallocates unused objects. • Garbage Collection is not predictable. The JVM decides when to run the Garbage Collector, meaning objects are not destroyed immediately after they become unreachable.
  • 7. • Java’s garbage collector automatically manages the lifecycle of objects. • When no references point to an object, it becomes eligible for garbage collection. • The garbage collector reclaims memory at its discretion, making memory management automated and simplifying development.
  • 8. How to Handle Cleanup in Java? • Since Java does not have destructors, it provides alternative mechanisms for cleanup: 1.Garbage Collection (Automatic) 2.finalize() method (Deprecated after Java 9) The Java compiler shows warnings if you use it. 3.try-with-resources (Best Practice) 4.Explicit close() methods (Manual Cleanup)
  • 9. Garbage Collection in Java • What is Garbage Collection? • Garbage Collection is an automatic memory management feature in Java. • It reclaims memory by destroying objects that are no longer in use. • The JVM decides when to run the garbage collector, making it non- deterministic. • Advantages: • Reduces the risk of memory leaks. • Simplifies memory management for developers.
  • 10. Advantages of Destructors • Automatic Resource Management: By automating the process of freeing up memory and other resources, Java's garbage collector lowers the possibility of memory leaks and improper resource management. • Simplifies Programming: By eliminating the need for developers to manually monitor and release memory, programming becomes simpler and less prone to error. • Enhances Performance: By effectively handling memory allocation and deallocation, automated memory management can aid in performance optimization.
  • 11. Java finalize() Method • Java provides an alternative way to do the same. • The Java Object class provides the finalize() method that works the same as the destructor. The syntax of the finalize() method is as follows: • Before Java 9, Java allowed the use of the finalize() method to define cleanup tasks before the object is garbage collected.
  • 12. Finalize() Method (Deprecated) • Java finalize() Method • The finalize() method was used to perform cleanup tasks before an object was garbage collected. • Syntax: • java • Copy • protected void finalize() throws Throwable • { • // Cleanup code • } • Deprecated after Java 9: Due to its unreliable execution and performance overhead. • Alternative: Use try-with-resources or explicit close() methods for resource cleanup.
  • 13. Best Practices for Resource Cleanup • Best Practices for Handling Cleanup in Java: 1.Use try-with-resources: Automatically closes resources like files, sockets, and database connections. 2.java try (FileInputStream fis = new FileInputStream("file.txt")) { // Use the resource } catch (IOException e) { e.printStackTrace(); } 2. Implement AutoCloseable: Create custom resources that can be used with try-with- resources. 3. Avoid finalize(): Use explicit cleanup methods instead.
  • 14. Conclusion • Key Takeaways: • Java does not have explicit destructors but uses Garbage Collection for automatic memory management. • The finalize() method is deprecated; use try-with- resources or close() methods for cleanup. • Automatic memory management simplifies programming and reduces the risk of memory leaks. • Always follow best practices for resource cleanup to ensure efficient and reliable code.