Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
Now Reading
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Finalize method executes a code of statements/closed operation. Although garbage collection in Java is automated, you may need to perform some manual clean-up operations before garbage collection is done. This is where you will need to use the finalize() method.
In Java, the garbage collector only collects objects created by new keywords. When new keywords do not create the objects, the garbage collector uses finalize method to perform clean-up processing.
In this tutorial, you will learn about the finalize method in Java and its utility to the programmer. We will start by seeing how the garbage collector works and how the garbage collection and finalize() method in Java work in conjunction. Further, we will understand the cleanup activity of finalize() method, finalization, etc., while looking at the syntax of finalize() Method in Java.
We will also look at how the finalize() method works in various scenarios and the lifetime of a finalized object in Java. We will also look at the alternatives of finalize in Java and understand how relying solely on finalize in Java may not be wise.
Whenever an object is unreferenced in Java programming, the garbage collector automatically reclaims the unused runtime memory. This has two benefits:
Now, we will see how this works by the following three ways to unreferenced objects:
import java.util.ArrayList;
public class AnonymousObjectsExample {
public static void main(String[] args) {
// Creating and using an anonymous object of StringBuilder
String result = new StringBuilder("Hello, ")
.append("John")
.append("!")
.toString();
System.out.println(result);
// Creating and using an anonymous object of ArrayList
int sum = new ArrayList<Integer>() {{
add(10);
add(20);
add(30);
}}.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
}
}
public class NullReferenceExample {
public static void main(String[] args) {
// Creating an object
MyClass obj = new MyClass();
// Nulling the reference
obj = null;
// Perform some other operations
// ...
}
}
class MyClass {
// A class definition
// ...
// You can include some class members and methods here
// ...
// Override finalize() method to observe garbage collection
@Override
protected void finalize() throws Throwable {
System.out.println("Finalizing an instance of MyClass");
}
}
public class ReferenceAssignmentExample {
public static void main(String[] args) {
// Creating objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// Assigning reference to another object
obj1 = obj2;
// Perform some other operations
// ...
}
}
class MyClass {
// A class definition
// ...
// You can include some class members and methods here
// ...
// Override finalize() method to observe garbage collection
@Override
protected void finalize() throws Throwable {
System.out.println("Finalizing an instance of MyClass");
}
}
As it was mentioned earlier, this method is used before garbage collection. Always remember that the finalize() method comes protected under the object class, and it is defined as protected void finalize(){}.
We will see how this works with an example:
public class FinalizeMethodExample {
public static void main(String[] args) {
// Creating objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// Nullifying references
obj1 = null;
obj2 = null;
// Requesting garbage collection
System.gc();
// Perform some other operations
// ...
}
}
class MyClass {
// A class definition
// ...
// You can include some class members and methods here
// ...
// Override finalize() method
@Override
protected void finalize() throws Throwable {
try {
System.out.println("Finalizing an instance of MyClass");
// Perform any necessary cleanup or finalization tasks
// ...
} finally {
super.finalize();
}
}
}
In this example, we create two instances of the MyClass class: obj1 and obj2. Both objects are allocated in a heap and are initially reachable through their respective reference variables.
Next, we nullify the references obj1 and obj2 by assigning null to them. This makes the objects eligible for garbage collection because no active references are pointing to them.
After nullifying the references, we explicitly request garbage collection by calling System.gc(). This suggests to the JVM that it's a suitable time to perform garbage collection and reclaim the memory occupied by the ‘unreachable’ objects.
During the garbage collection, the JVM identifies the objects without active references and invokes the finalize() method on each. In the MyClass class, we have overridden the finalize() method to include any necessary cleanup or finalization tasks. In this example, we simply print a message indicating when the objects are finalized.
It's important to note that the finalize() method is not guaranteed to be called immediately after an object becomes eligible for garbage collection. The JVM determines when to run the finalization process based on its own algorithms and memory management strategies. The finalize() method is called just before the object is garbage collected, allowing it to perform any necessary cleanup operations.
The cleanup activity is done by the finalize() method in Java. To understand cleanup activity, consider the following scenario:
Let us consider that your object is not created using new. But, the garbage collector can only recognize objects created by new keywords. In such cases, you will need to use the finalize() method, which helps to define your class.
Before the garbage collector goes on to release the storage that is taken up by your object, it calls upon finalize(), and only after the following garbage collection passes the memory will be reclaimed by it.
Final | Finally | Finalize() |
---|---|---|
It is a type of keyword in Java that does not allow any change in the value of a variable, prevents any method from overriding, and restricts any extension of a class or the formation of a subclass of a superclass. | It is a block used in Java for the execution of the code that it contains regardless of whether an exception is thrown. | It is a method in Java that helps in cleanup processing on your object before the garbage collector can reclaim it. |
Finalize() Method in Java might be used in the following scenarios:
You can use finalize() Method to provide a custom clean-up procedure to your object
You can use finalize() method for the following reasons:
Overriding provides subclasses with the ability to provide for its method implementation defined in its superclass.
To override the finalize() method in a Java class, follow these steps:
Example:
public class MyClass {
// Class members and methods go here
@Override
protected void finalize() throws Throwable {
try {
// Perform cleanup or finalization tasks here
// ...
} finally {
super.finalize();
}
}
public static void main(String[] args) {
// Create an instance of MyClass
MyClass myObject = new MyClass();
// Perform some operations
// ...
// Set the reference to null to make the object eligible for garbage collection
myObject = null;
// Request garbage collection
System.gc();
// Perform some other operations
// ...
}
}
It's important to note that the finalize() method is generally discouraged for critical resource cleanup or finalization tasks. It's recommended to use explicit resource management techniques, such as try-with-resources, to ensure proper resource release and cleanup.
Let us look at how finalize() method works in two different scenarios:
If an object does not have the finalize() method overridden, the garbage collector will skip calling any specific finalization logic for that object. In this case, the object will still be eligible for garbage collection like any other object, but it won't have a chance to perform any custom cleanup tasks before being reclaimed.
In some scenarios, an object can be "resurrected" during its finalization process. If an object's finalize() method resurrects the object by creating a new strong reference to it or adding it to some reachable data structure, the object will become reachable again and will not be garbage collected. This scenario is generally discouraged, as it can lead to unpredictable behavior and interfere with the normal garbage collection process.
The lifetime of your object in Java employing finalize() method passes through several stages. These stages are as follows:
The disadvantages of Finalizers are as follows:
Some of the alternatives to finalize() method are as follows:
We learned that by using finalize() method, you can manually perform cleanup operations before the garbage collector can reclaim it. We explored the various advantages and disadvantages of using finalize() method, such as potential risks and performance issues, and also got to know some of the alternatives for finalize(). However, it is best not to heavily depend upon finalize() method and to use the alternatives as suggested for better and optimized performance of your program.
Learn more about finalize() method and other Java concepts by enrolling in a professional course at online learning platforms like upGrad.
1. When is the finalize() method called?
Finalize() method is called before reclaiming your object by the garbage collector.
2. How many times can the finalize() Method be called for the same object?
You can use finalize() Method only once for an object.
3. Can I override finalize() Method in a subclass?
Yes, you can override the finalize() method in Java for a specific implementation.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...