by Dinesh Thakur Category: Control Structures

final: Variables are useful when you need to store information that can change as the program runs. However, there may be certain situations in the program in which the value of the variable should not be allowed to modify. It is accomplished using a particular type of variable known as the final variable. The final variable also called constant variable. It is a variable with a value that cannot modify during the execution of the program.

The Final keyword used when we want restrictions applied to a method, class, and variable. We can’t override the Final method, inherit the Final class or change the Final variable. To declare a final variable, use the final keyword before the variable declaration and initialize it with a value. Its syntax is

final datatype varName = value;
For example:
final double PI = 3.141592;

This statement declares a variable PI of type double which initialized to 3.141592, that cannot be modified. If an attempt is made to modify a final variable after it initialized, the compiler issues an error message "cannot assign a value to final variable PI."
You can also defer the initialization of the final variable, such a final variable known as a blank final. However, it must be initialized before it used.
Final variables are beneficial when one need to prevent accidental change to method parameters and with variables accessed by anonymous class.

Now consider a program to calculate the area of the circle,

//Area of the circle
public class AreaCircle {
    public static void main(String[] args){
        int r =10;//initializing radius
        final double PI =3.141592;//final variable
        double area;
        //PI = 3.142; will generate an error
        area = PI * r * r;
        System.out.println("Area of circle is -->"+area);

Output: Area of the circle is -- >314.1592
NOTE: It is recommended to declare a final variable in uppercase

finally: The finally block always executes when the try block exits, except System.exit(0) call. If an exception occurs inside a try block and there is no matching catch block, the method terminates without further executing any lines of code from that method. For example, suppose you may want to close a file that has opened even if your program could not read from the file for some reason. In other words, you want to close the file irrespective whether the read is successful or not. If you want that some lines of code must be executed regardless of whether or not there is matching catch block, put those lines inside the finally block.

The finally block is used to release system resources and perform any cleanup required by the code in the try block. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The finally block consist of finally keyword followed by the code enclosed in curly braces. Just like a catch block, a finally block is associated with a particular try block and must appear after the last catch block. If there are no catch blocks, then you can place the finally block immediately after the try block.

The general form of a try statement with finally block is

try {
    //statement that can throw exceptions
catch(exception_type identifier) {
    //statements executed after exception is thrown
finally {
     //statements which executed regardless of whether or not

     //exceptions are thrown

Let us consider three cases when the try-catch block executes only with the finally block.

Case A: If the try block succeeds (i.e., no exception is thrown), the flow of control reaches the end of the try block and proceeds to the finally block by skipping over the catch blocks. When the finally block completes, the rest of the method continues.

Case B: If a try block fails (i.e., an exception is thrown), the flow control immediately move to the appropriate catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues.

Case C: If the try or catch block has a return statement, the finally block still get executed before control transfers to its new destination. Now let us consider a program that demonstrates the use of finally block,

use of finally block

Output: divide by zero
Inside finally block
End of main method
NOTE: The finally block always executed except when the try or catch invokes a System.Exit() method, which causes the Java interpreter to stop running.

finalize(): Garbage collection automatically frees us the memory resources used by objects, but objects can hold other kinds of resources, such as open files and network collections. The garbage collector cannot free these resources for you. For this, we need to write a finalize() method for any object that needs to perform such tasks as closing files, terminating network connections and so on. The finalize() method declared in the java.lang.Object class.

A finalize() method is an instance method that takes no arguments and returns no value. There can be only one finalize() method per class. A finalize() method can throw an exception or error, but when the garbage collector automatically invokes it, any exception or error it throws is ignored and serves only to cause the method to return.

Before an object gets garbage collected, the garbage collector gives the object an opportunity to clean up itself through a call to the object's finalize() method. This method is called automatically by Java before an object finally destroyed, and space it occupies in memory is released. The finalize() method takes the following form,

protected void finalize() {

  //clean up code by you


Here, the keyword protected is an access specifier that prevents access to the finalize method by code defined outside the class. This code will explain it better:

class FinalizeExample {
   public void finalize() {
      System.out.println("Finalize is called");
   public static void main(String args[]) {
         FinalizeExample f1 = new FinalizeExample();
         FinalizeExample f2 = new FinalizeExample();
         f1 = null;
         f2 = null;

This method is useful when

• Your class object use resources that are not within the Java environment and are not guaranteed to be released by the object itself.· For example Graphics resources, fonts, etc. that are supplied by the host operating system.
• To record the fact that the object destroyed. For example: To count the numbers of objects that were in memory rather than created. Writing Java classes that interface to native platform code with native methods. In such a case, the native implementation can allocate memory or other resources that are not under the control of the garbage collector and need to reclaimed explicitly.
A problem with the finalize() method is that you never know when or if the finalize() method called. It is because the garbage collector is not guaranteed to execute at a specified time. So one should avoid using the finalize() method and when you do so you should write it with great care.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles