{"id":25530404,"date":"2022-06-26T20:00:07","date_gmt":"2022-06-26T14:30:07","guid":{"rendered":"https:\/\/entri.app\/blog\/?p=25530404"},"modified":"2022-11-19T17:20:13","modified_gmt":"2022-11-19T11:50:13","slug":"what-is-the-use-of-destructor-in-java","status":"publish","type":"post","link":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/","title":{"rendered":"What is the Use of Destructor in Java?"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_79_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-69e66d995de52\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-69e66d995de52\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#1_Safe_Deallocation\" >1) Safe Deallocation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#2_Proper_Resource_Management\" >2) Proper Resource Management<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#3_Error_Handling\" >3) Error Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#4_Memory_Optimization\" >4) Memory Optimization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#5_Exception_Safety\" >5) Exception Safety<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#6_Supporting_Class_Friends\" >6) Supporting Class Friends<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#7_Supporting_Interface_Implementations\" >7) Supporting Interface Implementations<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#8_Factory_Method_Pattern_Support\" >8) Factory Method Pattern Support<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#9_Resource_Cleanup_with_Standard_Java_Classes\" >9) Resource Cleanup with Standard Java Classes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#10_Finalizer_Replaces_Destructor\" >10) Finalizer Replaces Destructor<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><span data-slate-fragment=\"JTVCJTdCJTIydHlwZSUyMiUzQSUyMnBhcmFncmFwaCUyMiUyQyUyMmNoaWxkcmVuJTIyJTNBJTVCJTdCJTIydGV4dCUyMiUzQSUyMllvdSUyMGFyZSUyMGFscmVhZHklMjBhd2FyZSUyMG9mJTIwdGhlJTIwdXNlcyUyMG9mJTIwQ29uc3RydWN0b3IlMjBhbmQlMjBob3clMjBpdCUyMHdvcmtzJTIwaW4lMjBKYXZhJTIwUHJvZ3JhbW1pbmclMjBMYW5ndWFnZS4lMjBCdXQlMjBoYXZlJTIweW91JTIwZXZlciUyMHRob3VnaHQlMjBhYm91dCUyMERlc3RydWN0b3IlM0YlMjBEZXN0cnVjdG9yJTIwYW5kJTIwQ29uc3RydWN0b3IlMjB3b3JrJTIwdG9nZXRoZXIlMjB0byUyMHBlcmZvcm0lMjB0aGVpciUyMGZ1bmN0aW9ucyUyQyUyMGJ1dCUyMHdoYXQlMjBleGFjdGx5JTIwZG9lcyUyMERlc3RydWN0b3IlMjBkbyUzRiUyMFdoYXQlMjBpcyUyMHRoZSUyMHVzZSUyMG9mJTIwRGVzdHJ1Y3RvciUyMGluJTIwSmF2YSUzRiUyMEluJTIwdGhpcyUyMGFydGljbGUlMkMlMjB3ZSUyMHdpbGwlMjBiZSUyMGFuc3dlcmluZyUyMGFsbCUyMHRoZXNlJTIwcXVlc3Rpb25zJTIwYWJvdXQlMjBEZXN0cnVjdG9yJTIwYW5kJTIwaXRzJTIwdXNlcyUyMGluJTIwSmF2YSUyMHByb2dyYW1taW5nJTIwbGFuZ3VhZ2UuJTIyJTdEJTVEJTdEJTVE\">You are already aware of the uses of Constructor and how it works in Java Programming Language. But have you ever thought about Destructor? Destructor and Constructor work together to perform their functions, but what exactly does Destructor do? What are types of destructor in java? In this article, we will be answering all these questions about Destructor and its uses in the <a href=\"https:\/\/entri.app\/blog\/what-is-hiding-in-java-and-how-to-implement-it\/\" target=\"_blank\" rel=\"noopener\">Java programming<\/a> language. <\/span>The need to release all the resources when an object goes out of scope becomes important as you make your Java applications more complex. When you use the destructor, it releases resources that are no longer being used, which makes your code cleaner and more efficient and helps improve the performance of your application.<\/p>\n<p><a href=\"https:\/\/entri.sng.link\/Bcofz\/yeoy\/ojyv\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-25520997 size-full\" src=\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/04\/Python-and-Machine-Learning-Rectangle.png\" alt=\"\" width=\"970\" height=\"250\" srcset=\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/04\/Python-and-Machine-Learning-Rectangle.png 970w, https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/04\/Python-and-Machine-Learning-Rectangle-300x77.png 300w, https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/04\/Python-and-Machine-Learning-Rectangle-768x198.png 768w, https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/04\/Python-and-Machine-Learning-Rectangle-750x193.png 750w\" sizes=\"auto, (max-width: 970px) 100vw, 970px\" \/><\/a><\/p>\n<p>The destructor provides one more level of resource cleanup support that\u2019s not available in languages such as C++ or C#. In this article, we will go over reasons why you should use a destructor in Java and learn how to implement it properly in your projects. <span data-slate-fragment=\"JTVCJTdCJTIydHlwZSUyMiUzQSUyMnBhcmFncmFwaCUyMiUyQyUyMmNoaWxkcmVuJTIyJTNBJTVCJTdCJTIydGV4dCUyMiUzQSUyMkRlc3RydWN0b3JzJTIwaGF2ZSUyMG1hbnklMjB1c2VzJTIwYW5kJTIwYmVuZWZpdHMlMkMlMjBidXQlMjB5b3UlMjBtYXklMjBub3QlMjBldmVuJTIwcmVhbGl6ZSUyMHRoYXQlMjB5b3UlMjBjYW4lMjB1c2UlMjB0aGVtJTIwaW4lMjBKYXZhJTIwd2hlbiUyMHlvdSUyMGZpcnN0JTIwc3RhcnQlMjBvdXQlMjB1c2luZyUyMHRoZSUyMGxhbmd1YWdlLiUyMElmJTIweW91JUUyJTgwJTk5cmUlMjBmYW1pbGlhciUyMHdpdGglMjBDJTJCJTJCJTJDJTIwdGhlbiUyMGRlc3RydWN0b3JzJTIwd2lsbCUyMGJlJTIwc2Vjb25kJTIwbmF0dXJlJTIwdG8lMjB5b3UlMkMlMjBidXQlMjB5b3UlMjBjYW4lMjB1c2UlMjB0aGVtJTIwd2l0aG91dCUyMHdvcnJ5aW5nJTIwYWJvdXQlMjB0aGUlMjBleHRyYSUyMHN5bnRheCUyMHRoYXQlMjBDJTJCJTJCJTIwcmVxdWlyZXMuJTIwTWFueSUyMGRldmVsb3BlcnMlMjBkbyUyMG5vdCUyMGtub3clMjB3aHklMjB0aGV5JTIwc2hvdWxkJTIwZXZlbiUyMGJvdGhlciUyMHdpdGglMjB1c2luZyUyMGRlc3RydWN0b3JzJTJDJTIwc28lMjB0aGlzJTIwZ3VpZGUlMjB3aWxsJTIwaGVscCUyMGV4cGxhaW4lMjB0aGUlMjB2YWx1ZSUyMG9mJTIwdXNpbmclMjB0aGVzZSUyMGNvbnN0cnVjdHMlMjBpbiUyMHlvdXIlMjBjb2RlJTIwYW5kJTIwcG90ZW50aWFsbHklMjBhbnN3ZXIlMjBhbnklMjBxdWVzdGlvbnMlMjB0aGF0JTIweW91JTIwbWF5JTIwaGF2ZSUyMGFib3V0JTIwd2h5JTIwaXQncyUyMHZhbHVhYmxlJTIwdG8lMjB1c2UlMjBkZXN0cnVjdG9ycyUyMGluJTIwSmF2YSUyMGFwcGxpY2F0aW9ucy4lMjIlN0QlNUQlN0QlNUQ=\">Destructors have many uses and benefits, but you may not even realize that you can use them in Java when you first start out using <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">the language<\/a>. If you\u2019re familiar with C++, then destructors will be second nature to you, but you can use them without worrying about the extra syntax that C++ requires. Many developers do not know why they should even bother with using destructors, so this guide will help explain the value of using these constructs in your code and potentially answer any questions that you may have about why it&#8217;s valuable to use destructors in Java applications.<\/span><\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">To know more about java programming in the Entri App!<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"1_Safe_Deallocation\"><\/span><strong>1) Safe Deallocation<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A destructor, or finalizer, is invoked just before an object is destroyed. The C++ language ensures that every object that is created will eventually be destroyed and thus run its destructor method by employing garbage collection. Java doesn\u2019t do garbage collection; objects must be explicitly deallocated to avoid memory leaks. Without a destructor, you would have to specifically delete all references to an object in order for it to be deallocated when its job was done, which can result in subtle errors as well as hard-to-find bugs. A destructor also frees developers from having to write cleanup code themselves (sometimes known as housekeeping code), making life easier for everyone involved and <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">reducing overall<\/a> maintenance costs. As such, any time you create an object, whether it\u2019s on the heap or on the stack, it should always have a destructor. In addition to freeing up developer time, avoiding messy cleanup code and improving reliability through automatic deallocation of resources means more reliable applications that need less testing. Fewer defects mean happier users\u2014who are likely to use your software again in the future\u2014and happier managers who don&#8217;t have to worry about hiring more testers and dealing with increased support calls. In other words: fewer problems mean more profit!<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">Enroll in our latest java programming course in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"2_Proper_Resource_Management\"><\/span><strong>2) Proper Resource Management<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Objects are one of the main features of object-oriented programming (OOP), and it\u2019s important to understand how to use them properly. Simply having a reference to an object doesn\u2019t mean you have access to all its resources; when you no longer need those resources, you must be able to release them so they can be reclaimed by your application. The easiest way to do that is by using what&#8217;s called a destructor\u2014and it&#8217;s not as scary as it sounds. Here are 10 reasons why you should <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">use destructors<\/a> in your next Java project! There are many reasons for using destructors. For starters, if you don&#8217;t properly free up your objects&#8217; memory or other resources after releasing references to them, you run into potential resource leaks. This will eventually cause a serious performance issue with your program as each new instance uses more and more memory until there isn&#8217;t enough left over for other processes that might need it. It may even cause an OutOfMemoryError, which will result in poor user experience at best or failure of services at worst.<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">Get free placement assistance with the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"3_Error_Handling\"><\/span><strong>3) Error Handling<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A destructor does not need to be used for error handling. A destructor runs when an object is destroyed, which occurs naturally at runtime. Errors usually occur at runtime as well and can be handled using a try-catch block. For example, you can use try-catch blocks to check whether an object has been initialized or if an exception has occurred during initialization (preventing your program from continuing). If your program doesn\u2019t have an error handler built into it, you can add one manually by creating a new method with System.exit() as its return type and placing it outside of any loops or conditional statements. This way, no matter where execution is currently located in your code, control will return to Main after <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">your destructors<\/a> run. A destructor also doesn&#8217;t need to be used for memory management. A destructor does not free up memory; instead, it&#8217;s meant to clean up objects before they are disposed of so that they do not contain dangling pointers. The finalize() method is designed specifically for memory management; however, there are two problems with relying on finalize(). First, finalize() isn&#8217;t guaranteed to execute until JVM shutdown because garbage collection might take place between two calls to finalize(). Second, you cannot tell how much time has passed since an object was created or who called finalize(), making it difficult\u2014if not impossible\u2014to manage cleanup tasks accordingly.<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">Get the latest updates on java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"4_Memory_Optimization\"><\/span><strong>4) Memory Optimization<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Destructors are sometimes used for memory optimization, especially when it comes to removing event listeners. When you remove an event listener from a class, that class needs to remove any references to it. In order to do so, it must first invoke its own destructor. If you&#8217;re not careful, though, and add your own method calls before invoking your destructor, then you risk <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">adding some<\/a> un-optimized code at just the wrong time. For example public void onClick(View v) { \/\/ Do something here } \/\/ Don&#8217;t forget to call super()! @Override public void onClick(View v) { \/\/ Call another method or perform work here super(); \/\/ Invoke our destructor, which will remove all of our event listeners! mListener = null; } This is obviously an over-simplified example but hopefully it illustrates my point: you don&#8217;t want to put anything after calling your superclass&#8217; methods unless you absolutely have to. So if you need to add additional functionality, put it inside of a separate function and make sure that function is called last (i.e., after all, other methods). Or better yet: move any extra functionality into a separate interface or abstract class and have both classes implement that interface\/abstract class instead of putting logic directly into them (which would require overriding those methods anyway).<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">To know more about java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"5_Exception_Safety\"><\/span><strong>5) Exception Safety<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A destructor allows you to free any resources that were allocated as part of an object\u2019s construction. If your program allocates memory or opens a file handle when an object is created, it\u2019s best to free that memory or close that file handle before disposing of it. Without a destructor, it\u2019s up to you\u2014and if there are multiple developers on your team, chances are good<a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\"> someone will<\/a> forget and leave you with orphaned objects floating around in your code. A destructor helps avoid these kinds of bugs. When using exceptions for error handling, it\u2019s important to have cleanup code even if something fails\u2014otherwise, you risk leaving abandoned objects lying around and potentially running into memory leaks and other similar problems. For example, consider what happens if you open a file: try { FileInputStream fis = new FileInputStream(myfile); } catch (FileNotFoundException e) { \/\/ do nothing } Here we don&#8217;t do anything about our open stream because we don&#8217;t want to throw an exception. The problem is that our stream remains open until garbage collection occurs which could be never! This could cause some serious issues down the road.<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">Get the latest updates on java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"6_Supporting_Class_Friends\"><\/span><strong>6) Supporting Class Friends<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When you declare a base class, like Animal, you are also allowed to define virtual methods for that class. Virtual methods are ones that allow subclasses to override them with their own implementation. Because these methods can be overridden, you need to ensure that any resources those methods create will be released properly when an instance of your class is destroyed. To do so, you can make these resource-managing methods final, but then subclasses will have no way of modifying them (since they&#8217;re final). That&#8217;s where destructors come into play: If any non-final base class method creates resources (like files), it needs to be coupled with a custom type\u00a0of destructor in java in your derived classes. That destructor will close <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">those resources<\/a> and clean up before the instance is destroyed. For example, if you had a class called Animal that had a constructor and some sort of life cycle method, both would need to be coupled with appropriate destructors. For example: public class Cat extends Animal { \/\/ &#8230; public void lifeCycle() { \/\/ &#8230; } @Override protected void destroy() { \/\/ &#8230; } } In addition to closing down your system gracefully, implementing destructors allows you to handle exceptions thrown during construction or destruction. If an exception occurs during construction or destruction, Java automatically passes control over to its garbage collector (GC) process. The GC processes all objects in memory until there are none left; at which point it destroys itself. By default, all objects get garbage collected when they go out of scope\u2014even if they aren&#8217;t created by new!<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">To know more about java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"7_Supporting_Interface_Implementations\"><\/span><strong>7) Supporting Interface Implementations<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In an object-oriented programming language, an interface is a way to define how different classes can behave when specific actions are taken against them. When you take actions like calling methods or setting properties, you&#8217;re essentially working with objects. There&#8217;s more to it than that (see our slideshow below for more), but at its most basic level, a class is nothing more than a <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">blueprint for<\/a> making objects. The class alone doesn&#8217;t actually contain any code\u2014you need something else to fill in that space, and those things are called object instances. So what does all of that have to do with destructors? Well, in Java, every instance of a class has what&#8217;s known as a constructor. A constructor is responsible for initializing each new object instance so that it&#8217;s ready to be used by other parts of your program. But what happens if you want some code run after your constructor has finished? That&#8217;s where destructors come into play. They work similarly to constructors except they run once your object instance has been destroyed\u2014in other words, once it no longer exists within memory. So why would you want one?<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">Get the latest updates on java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"8_Factory_Method_Pattern_Support\"><\/span><strong>8) Factory Method Pattern Support<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>One way to make your classes easier to test is to use factory methods for creating your objects. Factory methods usually return an instance of an object of some other class, and these factory methods let you define code that creates new instances for you during testing. When you create objects manually during normal runtime, then use these same classes\u2019 constructors when testing, your tests may end up creating real implementations instead of their mock versions. One way around that problem is to use factory methods as well; they ensure that only mock implementations are created during testing and they allow you to control how those mock implementations are created. For example, you can use a <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">factory method<\/a> to create your mock implementation and pass it into another method for further testing. As another example, suppose you have a large class with many dependencies\u2014this large class would be hard to test without using dependency injection (DI). Using DI will help isolate your tests from all but one or two dependencies at a time. If you want to do DI with constructor injection (which I recommend), then using factory methods will give you more flexibility in isolating which constructor gets called than if you were doing DI with setter injection (which I don&#8217;t recommend).<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">To know more about java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"9_Resource_Cleanup_with_Standard_Java_Classes\"><\/span><strong>9) Resource Cleanup with Standard Java Classes<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The majority of languages have support for resource cleanup through destructors. With an automatic garbage collector, you don\u2019t really need to worry about cleaning up objects with these types of resources because it will automatically be collected. However, sometimes there are resources that will not be immediately cleaned up or accessed by your garbage collector due to leaks and other factors. Your garbage collector won\u2019t be able to clean up everything all at once, so what should you do? Well, one option is to use your own custom class that has a types of destructor in java. This method can then call methods on classes like FileInputStream and FileOutputStream to close them before they are collected. It\u2019s <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">important to<\/a> note that using standard Java classes is generally recommended over writing your own code. That said, if you have some unique requirements for your application (such as extra security), it might make sense to write something from scratch. Another reason why you may want to use your own class is that it allows you to run some custom logic when closing down certain resources. For example, let\u2019s say that we have a database connection object called dbConnection . If we are trying to close down our database connection without any data loss, we can call dbConnection.close() . But what if we wanted to run some additional logic first?<\/p>\n<h2><span class=\"ez-toc-section\" id=\"10_Finalizer_Replaces_Destructor\"><\/span><strong>10) Finalizer Replaces Destructor<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The real reason you should be using finalizers is that they have one big advantage over destructors: they guarantee destruction. As its name implies, a finalizer is invoked as soon as an object becomes eligible for garbage collection. This may happen immediately after creating an object or not until many minutes or even hours later (when memory is low and many objects are eligible for destruction). With destructors, you don\u2019t get such guarantees; you can only destroy objects immediately after using them (if at all). In most cases, there\u2019s no point to trying to track down when your objects become eligible for destruction\u2014you\u2019re better off letting Garbage Collector take care of it automatically. But what if your application runs into a memory issue? What if you want to ensure that certain resources aren\u2019t leaked? What if you need to do some clean-up work before destroying an object? For these scenarios, finalizers <a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\">are indispensable<\/a>. Finalizers are guaranteed to run sometime between now and eternity; with destructors, who knows when they will run! If you think about it, having multiple options for disposing of objects is actually more convenient than having just one. For example, if you had only destructors but wanted to manually invoke a method on an object from somewhere else in your code (for example, because something went wrong), you wouldn\u2019t be able to. Because every object has a finalizer and every class has a default implementation of Dispose(), however, any method can simply call GC.SuppressFinalize() on an instance. If there were no Dispose() method available at all, however, it would make sense to use GC.SuppressFinalize(). You never know when a piece of code might try calling another function on your object which relies on Dispose() being called earlier in time!<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/bit.ly\/3ELmCiA\">To know more about java programming in the Entri app<\/a><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When you create an object using class, it can keep track of its references by itself. But when it comes to Destroying them, They do not know how to release memory. That\u2019s why every object needs to implement a finalized method which is called when the garbage collector decides that no one is using the reference of that object anymore and they can be freed up. Now here comes<a href=\"https:\/\/entri.sng.link\/Bcofz\/uu8c\/w409\"> the problem<\/a> part, the Garbage collector has no idea whether particular class implements finalize or not so if that class doesn\u2019t implement finalize and you are calling a new Object() from some other place then the garbage collector may not free those up until the program is terminated because there could be someplace else still holding a reference of it. If you are interested to learn new coding skills, the Entri app will help you to acquire them very easily. Entri app is following a structural study plan so that the students can learn very easily. If you don&#8217;t have a coding background, it won&#8217;t be any problem. You can download the Entri app from the google play store and enroll in your favorite course.<\/p>\n<p style=\"text-align: center;\">\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You are already aware of the uses of Constructor and how it works in Java Programming Language. But have you ever thought about Destructor? Destructor and Constructor work together to perform their functions, but what exactly does Destructor do? What are types of destructor in java? In this article, we will be answering all these [&hellip;]<\/p>\n","protected":false},"author":93,"featured_media":25530405,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[802,1864,1882,1883,1881],"tags":[],"class_list":["post-25530404","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-articles","category-data-science-ml","category-java-programming","category-react-native","category-web-android-development"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.6 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>What is the Use of Destructor in Java? - Entri Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"What is the Use of Destructor in Java? - Entri Blog\" \/>\n<meta property=\"og:description\" content=\"You are already aware of the uses of Constructor and how it works in Java Programming Language. But have you ever thought about Destructor? Destructor and Constructor work together to perform their functions, but what exactly does Destructor do? What are types of destructor in java? In this article, we will be answering all these [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Entri Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/entri.me\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-06-26T14:30:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-19T11:50:13+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"820\" \/>\n\t<meta property=\"og:image:height\" content=\"615\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Akhil M G\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@entri_app\" \/>\n<meta name=\"twitter:site\" content=\"@entri_app\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Akhil M G\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\"},\"author\":{\"name\":\"Akhil M G\",\"@id\":\"https:\/\/entri.app\/blog\/#\/schema\/person\/875646423b2cce93c1bd5bc16850fff6\"},\"headline\":\"What is the Use of Destructor in Java?\",\"datePublished\":\"2022-06-26T14:30:07+00:00\",\"dateModified\":\"2022-11-19T11:50:13+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\"},\"wordCount\":2838,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/entri.app\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png\",\"articleSection\":[\"Articles\",\"Data Science and Machine Learning\",\"Java Programming\",\"React Native\",\"Web and Android Development\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\",\"url\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\",\"name\":\"What is the Use of Destructor in Java? - Entri Blog\",\"isPartOf\":{\"@id\":\"https:\/\/entri.app\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png\",\"datePublished\":\"2022-06-26T14:30:07+00:00\",\"dateModified\":\"2022-11-19T11:50:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage\",\"url\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png\",\"contentUrl\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png\",\"width\":820,\"height\":615,\"caption\":\"What is the Use of Destructor in Java?\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/entri.app\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Entri Skilling\",\"item\":\"https:\/\/entri.app\/blog\/category\/entri-skilling\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Java Programming\",\"item\":\"https:\/\/entri.app\/blog\/category\/entri-skilling\/java-programming\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"What is the Use of Destructor in Java?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/entri.app\/blog\/#website\",\"url\":\"https:\/\/entri.app\/blog\/\",\"name\":\"Entri Blog\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/entri.app\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/entri.app\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/entri.app\/blog\/#organization\",\"name\":\"Entri App\",\"url\":\"https:\/\/entri.app\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/entri.app\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2019\/10\/Entri-Logo-1.png\",\"contentUrl\":\"https:\/\/entri.app\/blog\/wp-content\/uploads\/2019\/10\/Entri-Logo-1.png\",\"width\":989,\"height\":446,\"caption\":\"Entri App\"},\"image\":{\"@id\":\"https:\/\/entri.app\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/entri.me\/\",\"https:\/\/x.com\/entri_app\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/entri.app\/blog\/#\/schema\/person\/875646423b2cce93c1bd5bc16850fff6\",\"name\":\"Akhil M G\",\"url\":\"https:\/\/entri.app\/blog\/author\/akhil\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"What is the Use of Destructor in Java? - Entri Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/","og_locale":"en_US","og_type":"article","og_title":"What is the Use of Destructor in Java? - Entri Blog","og_description":"You are already aware of the uses of Constructor and how it works in Java Programming Language. But have you ever thought about Destructor? Destructor and Constructor work together to perform their functions, but what exactly does Destructor do? What are types of destructor in java? In this article, we will be answering all these [&hellip;]","og_url":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/","og_site_name":"Entri Blog","article_publisher":"https:\/\/www.facebook.com\/entri.me\/","article_published_time":"2022-06-26T14:30:07+00:00","article_modified_time":"2022-11-19T11:50:13+00:00","og_image":[{"width":820,"height":615,"url":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png","type":"image\/png"}],"author":"Akhil M G","twitter_card":"summary_large_image","twitter_creator":"@entri_app","twitter_site":"@entri_app","twitter_misc":{"Written by":"Akhil M G","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#article","isPartOf":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/"},"author":{"name":"Akhil M G","@id":"https:\/\/entri.app\/blog\/#\/schema\/person\/875646423b2cce93c1bd5bc16850fff6"},"headline":"What is the Use of Destructor in Java?","datePublished":"2022-06-26T14:30:07+00:00","dateModified":"2022-11-19T11:50:13+00:00","mainEntityOfPage":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/"},"wordCount":2838,"commentCount":0,"publisher":{"@id":"https:\/\/entri.app\/blog\/#organization"},"image":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png","articleSection":["Articles","Data Science and Machine Learning","Java Programming","React Native","Web and Android Development"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/","url":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/","name":"What is the Use of Destructor in Java? - Entri Blog","isPartOf":{"@id":"https:\/\/entri.app\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage"},"image":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png","datePublished":"2022-06-26T14:30:07+00:00","dateModified":"2022-11-19T11:50:13+00:00","breadcrumb":{"@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#primaryimage","url":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png","contentUrl":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2022\/06\/Untitled-77-1.png","width":820,"height":615,"caption":"What is the Use of Destructor in Java?"},{"@type":"BreadcrumbList","@id":"https:\/\/entri.app\/blog\/what-is-the-use-of-destructor-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/entri.app\/blog\/"},{"@type":"ListItem","position":2,"name":"Entri Skilling","item":"https:\/\/entri.app\/blog\/category\/entri-skilling\/"},{"@type":"ListItem","position":3,"name":"Java Programming","item":"https:\/\/entri.app\/blog\/category\/entri-skilling\/java-programming\/"},{"@type":"ListItem","position":4,"name":"What is the Use of Destructor in Java?"}]},{"@type":"WebSite","@id":"https:\/\/entri.app\/blog\/#website","url":"https:\/\/entri.app\/blog\/","name":"Entri Blog","description":"","publisher":{"@id":"https:\/\/entri.app\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/entri.app\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/entri.app\/blog\/#organization","name":"Entri App","url":"https:\/\/entri.app\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/entri.app\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2019\/10\/Entri-Logo-1.png","contentUrl":"https:\/\/entri.app\/blog\/wp-content\/uploads\/2019\/10\/Entri-Logo-1.png","width":989,"height":446,"caption":"Entri App"},"image":{"@id":"https:\/\/entri.app\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/entri.me\/","https:\/\/x.com\/entri_app"]},{"@type":"Person","@id":"https:\/\/entri.app\/blog\/#\/schema\/person\/875646423b2cce93c1bd5bc16850fff6","name":"Akhil M G","url":"https:\/\/entri.app\/blog\/author\/akhil\/"}]}},"_links":{"self":[{"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/posts\/25530404","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/users\/93"}],"replies":[{"embeddable":true,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/comments?post=25530404"}],"version-history":[{"count":4,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/posts\/25530404\/revisions"}],"predecessor-version":[{"id":25547433,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/posts\/25530404\/revisions\/25547433"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/media\/25530405"}],"wp:attachment":[{"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/media?parent=25530404"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/categories?post=25530404"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/entri.app\/blog\/wp-json\/wp\/v2\/tags?post=25530404"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}