Final vs Finally and Finalize in Java: Key Differences and Usage. In Java, the terms final, finally, and finalize might seem similar, but they serve distinct purposes and are essential in different contexts. As a Java developer, understanding the subtle differences between these keywords is crucial for writing efficient and robust code. This article will delve into the definitions of final, finally, and finalize, provide programming examples for each, present a tabular comparison, and conclude with a better grasp of their usage in Java.
Final vs Finally vs and Finalize in Java Definition:
final:
In Java, the keyword final is used to declare constants, variables, and methods. When a variable is declared as final, its value cannot be changed after initialization, making it effectively a constant. Similarly, when a method is marked as final, it cannot be overridden by any subclass. This provides immutability and helps ensure data integrity and security in the code.
- Local Variables: A final local variable cannot be reassigned after its initial assignment in the method or block where it is declared.
- Fields: A final field in a class can be assigned a value only once, either during declaration or in the constructor.
- Methods: A final method in a class cannot be overridden by any subclass, ensuring the method’s implementation remains unchanged.
- Classes: A final class cannot be subclassed, making it impossible to extend or inherit from this class.
- Parameters: A final parameter inside a method ensures that the parameter value cannot be modified inside the method.
finally:
The final keyword is used in conjunction with try-catch blocks for exception handling. The code within the final block will always execute, regardless of whether an exception is thrown or not. This ensures that any critical cleanup or resource release operations are executed, even in the presence of exceptions.
- The finally block is used in conjunction with try-catch blocks to guarantee the execution of specific code, such as resource cleanup or closing files, irrespective of whether an exception occurs or not.
- It is generally used to release resources acquired within the try block, ensuring they are properly closed or released, even if an exception is thrown.
finalize:
The finalize method is a part of the Object class in Java and is called by the garbage collector before reclaiming the memory occupied by an object. Developers can override the finalize method to release any external resources used by the object, ensuring proper cleanup before the object is garbage collected.
- The finalize() method is automatically called by the garbage collector before an object is garbage collected and its memory is reclaimed.
- Developers can override this method in their classes to perform necessary cleanup tasks, such as closing open files, releasing database connections, or releasing other external resources associated with the object.
- It is important to note that the usage of finalize is discouraged due to its uncertain and unpredictable nature in terms of when the garbage collector will execute it.
Final vs Finally vs and Finalize in Java Programming Examples:
final Example:
public class FinalExample {
public static void main(String[] args) {
final int age = 30; // Declaration of a final variable
// age = 31; // Error: Cannot reassign a final variable
System.out.println("Age: " + age);
final String name = "John"; // Declaration of a final variable
// name = "Mike"; // Error: Cannot reassign a final variable
System.out.println("Name: " + name);
}
}
finally Example:
import java.io.*;
public class FinallyExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
// Code to read from the file
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
System.out.println("Error closing file: " + e.getMessage());
}
}
}
}
finalize Example:
public class FinalizeExample {
@Override
protected void finalize() {
// Code to release external resources used by the object
// Resource cleanup operations
}
public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
// Code to use the object
obj = null; // Object becomes eligible for garbage collection
System.gc(); // Request garbage collection (finalize will be called)
}
}
Final vs Finally vs and Finalize Comparison
Keyword | Purpose | Usage |
---|---|---|
final | Declares constants, variables, and methods with immutability and non-overridability features. | Constant variables, Immutable classes. |
finally | Ensures execution of code within try-catch blocks, regardless of exceptions. | Exception handling, Resource cleanup. |
finalize | Called by the garbage collector before object memory is reclaimed. | Resource cleanup, Object destruction. |
Conclusion:
In Java, the keywords final, finally, and finalize are crucial components with distinct functionalities.
The final keyword ensures immutability and non-overridability, finally guarantees the execution of critical code even during exception handling, and finalize allows resource cleanup before object destruction.
Related Articles:
- ArrayList vs Vector in Java Collection Framework
- Java Constructors its Types and differences
- Types of Inheritance in Java
- Interface vs. Inheritance in Java: Unraveling the Key Differences
- Final vs Finally vs and Finalize in Java: Key Differences and Usage
- HashMap vs. HashSet: Understanding the Key Differences
- Array vs. ArrayList: Understanding the Differences in Java
- Method Overloading vs Method Overriding | Java
- Single vs Multiple Inheritance with Example