In this blog we will see frequently asked interview question for java programmers What is final finalize and finally in java ? and usage for each.
final
In Java, the final
keyword is used to restrict the user from overriding a method, from changing the value of a variable or from extending a class
- Final Variables: When a variable is declared as
final
, its value cannot be changed once initialized. It becomes a constant.final int MAX_VALUE = 100;
- Final Methods: When a method is declared as
final
in a class, it cannot be overridden by subclasses.class Parent {
final void display() {
System.out.println("Parent class method.");
}
}
- Final Classes: When a class is declared as
final
, it cannot be extended (subclassed).
final class FinalClass { // Class implementation }
The final
keyword can be applied to variables, methods, and classes to achieve different levels of immutability and restriction in Java programming.
finalize
In Java, the finalize
method is a special method provided by the Object
class that is called by the garbage collector before reclaiming an object’s memory.
The finalize
method has the following characteristics:
- Syntax:
protected void finalize() throws Throwable { // Cleanup code }
- Purpose:
- It is used to perform cleanup operations before an object is garbage collected.
- It can be used to release system resources such as closing files, sockets, database connections, etc.
- Execution:
- The
finalize
method is automatically called by the garbage collector when it determines that there are no more references to the object. - The
finalize
method is called only once for each object before it is garbage collected.
- The
- Caution:
- It is not recommended to rely on the
finalize
method for critical resource cleanup as it is not guaranteed to be called immediately or at all. - It is considered a best practice to explicitly release resources using try-with-resources or explicit cleanup methods.
- It is not recommended to rely on the
In modern Java programming, it is recommended to use try-with-resources, explicit cleanup methods, or the AutoCloseable
interface for resource management instead of relying on the finalize
method.
Here is an example demonstrating the use of the finalize
method in Java:
package com.java.how2injava.keywords.finalize;
public class FinalizeSample {
public static void main(String[] args) {
Resource resource = new Resource();
// Nullify the reference to the object
resource = null;
// Request garbage collection
System.gc();
}
}
class Resource {
public Resource() {
System.out.println("Resource created.");
}
protected void finalize() {
System.out.println("Resource being finalized.");
// Cleanup operations
// Close files, release resources, etc.
}
}
In this example:
- We have a
Resource
class with afinalize
method that prints a message indicating that the resource is being finalized. - In the
main
method, we create an instance of theResource
class and then set the reference tonull
to make it eligible for garbage collection. - We then explicitly request garbage collection using
System.gc()
.
When the garbage collector runs, it will call the finalize
method of the Resource
object before reclaiming its memory. The message “Resource being finalized” will be printed to the console when the finalize
method is executed.
finally
In Java, the finally
keyword is used in conjunction with try-catch blocks to define a block of code that will be executed whether an exception is thrown or not. The finally
block is guaranteed to execute, even if an exception is thrown and caught.
The finally
block is typically used for cleanup operations such as closing resources (files, sockets, database connections) or releasing locks, regardless of whether an exception occurs or not.
Here is the syntax for a try-catch-finally block in Java:
try {
// suspected Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
} finally {
// Cleanup code that always executes
}
- If an exception is thrown in the try block, the catch block will handle the exception. After the catch block (if present), the finally block will be executed.
- If no exception is thrown, the code in the try block will execute, followed by the code in the finally block.
The finally
block is useful for ensuring that resources are properly released, even if exceptions occur. It is commonly used for closing resources that were opened in the try block.
Example:
package com.java.how2injava.exceptions;
import java.io.FileWriter;
import java.io.IOException;
public class FinallySample {
public static void main(String[] args) {
FileWriter writer = null;
try {
writer = new FileWriter("output.txt");
writer.write("Hello, World!");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
System.err.println("Error closing file: " + e.getMessage());
}
}
}
}
In this example, the finally
block ensures that the FileWriter
is closed, even if an exception occurs while writing to the file.
Sample programs are available on github.
Conclusion on final, finalize and finally :
In this blog we saw what is final, finalize and finally,
final
is used to create constants, prevent method overriding, and prevent inheritance.finally
is used intry-catch
blocks to define code that always gets executed.finalize
is a method called by the garbage collector before an object is garbage collected, but it is deprecated and not recommended for use.
Related topic Know, The Keywords In Java And Usage