Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

final, finally and finalize in Java

Last Updated on December 11, 2023 by Ankit Kochar

In the world of Java programming, precision in terminology is crucial, especially when it comes to the trio of "final," "finally," and "finalize." These concepts, although sharing linguistic similarities, serve distinct roles in Java code. Understanding their nuances is paramount for Java developers to ensure efficient, error-free, and robust software development. This exploration delves into the specific meanings and applications of "final," "finally," and "finalize" in Java, shedding light on their individual roles in the language’s syntax and functionality.

Before learning about the difference between final finally and finalize let us first understand each keyword one by one.

final Keyword in Java

The final keyword is used to declare a variable or method that cannot be modified or overridden. When we declare a variable as final, its value cannot be changed. Similarly, when a method is declared as final, it cannot be overridden by any subclass. In Java, it is also possible to declare a method that cannot be overridden by any subclass by using the final keyword.

The syntax for declaring a variable as final is given below:

final int varName = 10;

Here in the above statement, varName is declared as a final variable with an initial value of 10. Once varName is assigned a value, it cannot be changed. If we try to change the value of varName later in the program, we’ll get a compile-time error.

The use of the final keyword in Java is demonstrated in the example below.

class PrepBytes {  
    //declaring final variable  
    final int age = 18;  
    
    void display() {  
        // reassigning value to age variable   
        // gives compile time error  
        age = 55;  
    }  
      
    public static void main(String[] args) {  
    	PrepBytes obj = new PrepBytes();   
        obj.display();  
    }  
}

Output:

Main.java:8: error: cannot assign a value to final variable age
        age = 55;  
        ^
1 error

Explanation:
In the above code, we have declared a final variable named “age” and assigned it a value of 18. When we try to update the value of this variable to 55. It will show a Compile Time Error as shown in the Output.

finally Keyword in Java

The finally keyword is used in Java try-catch blocks to specify a block of code that will be executed regardless of whether an exception is thrown or not. Since the finally block is guaranteed to be executed, even if an exception is thrown, so finally block is often used in the cleanup operations, such as closing open files and releasing the resources.

This example demonstrates the usage of the finally Keyword in Java Exception Handling.

class PrepBytes{    
    public static void main(String args[]){   
    	try {    
    		System.out.println("Inside try block");  
         
        	// below code throws divide by zero exception  
        	int data=25/0;    
        	System.out.println(data);    
        }   
          
        // handles the Arithmetic Exception / Divide by zero exception  
        catch (ArithmeticException e){  
            System.out.println("Exception handled");  
            System.out.println(e);  
        }   
          
        // executes regardless of exception occurred or not   
        finally {  
            System.out.println("finally block is always executed");  
        }    
          
        System.out.println("rest of the code...");    
        }    
}

Output:

Inside try block
Exception handled
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...

Explanation:
In this example, we have used the try-catch blocks to catch the expected exceptions. The try block contains the part of the code which can throw exceptions. First, the try block is executed, and the “Inside try block” is printed, then the statement “int data = 25/0”, throws an error, so now the control transfers to the catch block. In the catch block first, “Exception handled” is printed, then the Type of error is printed. And at last, the finally block is executed, even if the exception occurs.

finalize Keyword in Java

The finalize method is a special method that is called by the garbage collector when an object is about to be destroyed. The finalize() method can be used to perform any necessary cleanup operations before the object is destroyed.

Here’s an example:

class PrepBytes{    
    // defining the finalize method   
    protected void finalize(){     
        System.out.println("Called the finalize() method");     
    }
    
    public static void main(String[] args){     
        PrepBytes obj = new PrepBytes();        
        // printing the hashcode   
        System.out.println("Hashcode is: " + obj.hashCode());           
        obj = null;   
        
        // calling the garbage collector using gc()   
        System.gc();     
        System.out.println("End of the garbage collection");     
    }     
        
}

Output:

Hashcode is: 804564176
End of the garbage collection
Called the finalize() method

Explanation:
In the above code, we first created an object of class PrepBytes, then we printed its hashcode to show that the object is created. And then we set the value of the object to null, then we called the garbage collector using the gc() function. Here when we called the garbage collector, it executes our used-defined “finalize()” method.

Now that we’ve seen some examples of how final, finally, and finalize are used, let’s explore their differences in more detail.

Difference Between final finally and finalize in Java

The main difference between final finally and finalize in Java are shown in table below.

Basis of Comparison final finally finalize
Definition final is a keyword used in Java to restrict the modification of a variable, method, or class. finally is a block used in Java to ensure that a section of code is always executed, even if an exception is thrown. finalize is a method in Java used to perform cleanup processing on an object before it is garbage collected.
Usage final is used to declare a variable, method, or class as unchangeable. finally is used after a try or catch block to execute code that must be run regardless of whether an exception is thrown or not. finalize is used to perform cleanup operations on an object, such as closing files or releasing other resources, before it is garbage collected.
Execution final is executed at compile-time. finally is executed at runtime. finalize is executed by the garbage collector before an object is destroyed.
Exception handling final is not used for exception handling. finally is used for exception handling. finalize is not used for exception handling.
Syntax final is used as a keyword to modify a variable, method, or class. finally is used as a block to execute a set of statements. finalize is used as a method to perform cleanup operations.

Conclusion
In conclusion, the trio of "final," "finally," and "finalize" encapsulates essential aspects of Java programming, each contributing uniquely to the language’s robustness and reliability. "Final" adds a layer of immutability to variables, methods, and classes, enhancing code stability. The "finally" block, as part of exception handling, ensures that critical cleanup operations occur, irrespective of whether an exception is thrown or not. Lastly, the "finalize" method facilitates resource management by providing an opportunity for object cleanup before garbage collection.
As Java continues to be a cornerstone of modern software development, a precise understanding of these concepts empowers developers to write efficient, maintainable, and error-resistant code.

Frequently Asked Questions (FAQs) related to final, finally and finalize in Java

Here are some Frequently Asked Questions based on the difference between final finally and finalize in Java.

1. What does the "final" keyword signify in Java?
The "final" keyword in Java is used to declare variables, methods, and classes. When applied to a variable, it indicates that the variable’s value cannot be changed. For methods, "final" signifies that the method cannot be overridden by subclasses, and for classes, it means that the class cannot be extended.

2. What is the purpose of the "finally" block in Java?
The "finally" block in Java is part of the try-catch-finally exception-handling mechanism. Code within the "finally" block is guaranteed to execute, whether an exception is thrown or not. This ensures that essential cleanup operations, such as releasing resources, occur regardless of the program’s execution path.

3. How does the "finalize" method contribute to Java’s memory management?
The "finalize" method is part of the Java Object class and is called by the garbage collector before reclaiming the memory occupied by an object. Developers can override this method to perform cleanup operations, such as releasing resources or closing connections, before the object is removed from memory.

4. Can a method be both "final" and "static" in Java?
Yes, a method in Java can be both "final" and "static." The "final" keyword signifies that the method cannot be overridden in subclasses, while "static" indicates that the method belongs to the class rather than instances of the class.

5. Are there alternatives to using "finalize" for resource cleanup in Java?
Yes, it is generally recommended to use alternatives to the "finalize" method for resource cleanup, such as implementing the AutoCloseable interface and using try-with-resources statements introduced in Java 7. These alternatives offer more predictable and efficient resource management.

6. When should one use the "finally" block as opposed to other exception handling constructs?
The "finally" block is suitable for code that must execute regardless of whether an exception is thrown or not. It is commonly used for cleanup operations, such as closing files or releasing resources. If cleanup code is essential, the "finally" block ensures it is executed in all scenarios, making it a crucial part of robust exception handling in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *