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 March 15, 2023 by Prepbytes

In Object Oriented Programming languages like Java, there are three keywords that are often used interchangeably: final, finally, and finalize. While they may look similar, they have different meanings and serve different purposes. Let us take a closer look at each of these keywords and learn about the difference between final finally and finalize in Java.

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.

Summary
In summary, final finally and finalize are three distinct keywords in Java that serve different purposes. final is used to define a constant variable, a method that cannot be overridden or a class that cannot be extended. finally is used in try-catch blocks to specify a block of code that will be executed regardless of whether an exception is thrown or not. Finally, finalize is used to perform any necessary cleanup operations before an object is destroyed by the garbage collector. It is important to understand the differences between these keywords and their usage in programming to avoid errors and unintended behavior.

Frequently Asked Questions (FAQs)

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

Ques 1. What happens if a final variable is modified?
Ans. If a final variable is modified, the program will not compile, and an error will be thrown.

Ques 2. Can a final method be overloaded?
Ans. Yes, a final method can be overloaded.

Ques 3. What happens if an exception is thrown in the finally block?
Ans. If an exception is thrown in the finally block, it will override any previous exceptions thrown by the try or catch blocks.

Ques 4. Is the finally block guaranteed to execute even if there is a return statement in the try block?
Ans. Yes, the finally block is guaranteed to execute even if there is a return statement in the try block.

Ques 5. Is the finalize method guaranteed to execute before an object is destroyed by the garbage collector?
Ans. No, the finalize method is not guaranteed to execute before an object is destroyed by the garbage collector.

Leave a Reply

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