Table of contents
1.
Introduction
2.
Example of Final Keyword
3.
Example of Finally Keyword
4.
Example of Finalize Keyword
5.
Frequently Asked Questions
5.1.
What is final finally and finalize in Java?
5.2.
What is the use of finalize keyword?
5.3.
What is finally keyword?
5.4.
Why Final keyword is used in Java?
5.5.
Why finally block is used?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Final vs Finally vs Finalize

Author soham Medewar
0 upvote

Introduction

The keywords final, finally, and finalize are used in exception handling in Java. Each of these terms serves a distinct purpose. The primary distinction between final, finally, and finalize is that final is an access modifier, finally is an exception handling block, and finalize is an object class function.

Final, finally and finalize

Furthermore, there are numerous distinctions between final, finally, and finalize. The following are the distinctions between final, finally, and finalize:

Key final finally finalize
Definition final is a keyword and access modifier that is used to restrict access to a class, method, or variable. Finally, the block in Java Exception Handling executes the critical function whether or not the exception occurs In Java, the finalize method is used to do cleanup procedures immediately before an object is garbage collected.
Applicable to With classes, methods, and variables, the final keyword is utilized. In exception handling, the finally block is usually associated with the try and catch block. The finalize() method is applied to objects.
Functionality

(1) Once declared, the final variable is fixed and cannot be changed.

(2) A subclass cannot override the final method.

(3) The final class is not inheritable.

(1) The finally block executes the critical code whether or not an exception occurs.

(2) The finally block cleans up all of the resources that were used in the try block.

Before an item is destroyed, cleaning tasks are carried out using the finalize method.
Execution Only when we call the final method is it actually used.

After the try-catch block, the finally block is carried out.

The exception has no bearing on how it is carried out.

Just before the object is destroyed, the finalize method is called.

 

Must Read Static Blocks In Java and Fibonacci Series in Java

Example of Final Keyword

final

Let's have a look at the example below where the final variable "name" is declared. It cannot be changed once it is stated.

Example.java

class Example{
	// declaring a final variable
	final String name = "Soham";

	void disp(){
		// reassigining the name variable
		// that throws compile time error
		name = "Ganesh";
	}

	public static void main(String[] args) {
		Example obj = new Example();
		// executing disp method;
		obj.disp();
	}
}
You can also try this code with Online Java Compiler
Run Code


Output

Example.java:8: error: cannot assign a value to final variable name
name = "Ganesh";
^
1 error
You can also try this code with Online Java Compiler
Run Code


Try it on online java compiler.
A variable has been designated final in the example above. The final keyword can also be used to designate methods and classes final.

Also see,  Swap Function in Java

Here's your problem of the day

Solving this problem will increase your chance to get selected in this company

Skill covered: Java

How do you declare an array in Java?

Choose another skill to practice

Example of Finally Keyword

finally

Let's look at the example below, where the catch block handles an exception that the Java code throws. After the try-catch block, the finally block is then run. Additionally, the remaining code runs normally as well.

Example.java

class Example{
	void disp(){
		try{
			System.out.println("Code inside try block");
			// arithmetic exception
			int val = 56/0;
			System.out.println(val);
		}
		catch(Exception e){ // handling exception
			System.out.println("Exception Handled Successfully");
			// printing exception
			System.out.println(e);
		}
		finally{
			// the code inside finally block is always executed
			System.out.println("This code is always executed");
		}
		// normally executing rest of the code
		System.out.println("remaining code ...");
	}
	public static void main(String[] args) {
		// creating object of the Example class
		Example obj = new Example();
		// executing disp method;
		obj.disp();
	}
}
You can also try this code with Online Java Compiler
Run Code


Output

Code inside try block
Exception Handled Successfully
java.lang.ArithmeticException: / by zero
This code is always executed
remaining code ...
You can also try this code with Online Java Compiler
Run Code

Example of Finalize Keyword

finalize

Example.java

class Example {    
    public static void main(String[] args){

        Example obj = new Example();        
        // printing the hashcode
        System.out.println("Hashcode : " + obj.hashCode());           
        obj = null;    

        // gc() is used to call garbage collector   
        System.gc();     
        System.out.println("End of the garbage collection");     
    }
    // defining the finalize method
    protected void finalize(){     
        System.out.println("Called the finalize() method");     
    }     
}
You can also try this code with Online Java Compiler
Run Code


Output

Hashcode : 498931366
End of the garbage collection
Called the finalize() method
You can also try this code with Online Java Compiler
Run Code


Also see, Duck Number in Java and Hashcode Method in Java

Frequently Asked Questions

What is final finally and finalize in Java?

In Java, the keyword final is used as an access modifier. In Java, the finally block is used for handling exceptions. Garbage collection in Java is handled via the method finalize.

What is the use of finalize keyword?

Before the current object is destroyed, cleanup actions can be taken on its unmanaged resources using the Finalize method. Because the method is protected, it can only be accessed by this class or a derived class.

What is finally keyword?

No matter if there is an exception or not, the finally keyword is used to run code (used with exceptions - try.. catch statements).

Why Final keyword is used in Java?

The final keyword is a non-access modifier that prevents changes to classes, attributes, and methods (impossible to inherit or override). When you want a variable, such as PI, to always store the same value, the final keyword is helpful (3.14159...). The phrase "modifier" refers to the last term.

Why finally block is used?

In Java, critical codes like clean-up code, such as shutting the file or the connection, are placed in the finally block. Regardless of whether an exception arises or is handled, the finally block always executes. Whether the exception happens or not, all the important statements are contained in the finally clause.

Conclusion

In this blog, we have read about the final, finally, and finalize in detail. After reading about the final, finally, and finalize in Java, are you not feeling excited to read/explore more articles on the topic of Java? Don't worry; Coding Ninjas has you covered. To learn, see Multilevel inheritance in JavaMultiple Inheritance in Java, and Static Binding vs Dynamic Binding.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy Coding!

Live masterclass