When to use Final, Finally and Finalize Methods in Java

Differences between Final, Finally and Finalize in Java

Final Keyword in Java

Final is a keyword or reserved word in Java.

The Final keyword in Java can be used in the following three ways:

  • Class
  • Method
  • Variables

Final Variable in Java

If a variable is declared as final then it cannot be reinitialized after it. Final variables are often declared with the static keyword in Java and treated as constant. Here is an example of a final variable in Java. Final variables are by default read-only.

Final member variables need to be initialized at the time of declaration or we can also initialize it inside the constructor. If we fail to do so it will result in a compilation error.

The Final keyword can be applied with variables that have no value and then it is called a blank final variable. A blank final variable forces the constructors to initialize it. It can be static also and will be initialized in the static block of code only.

  • It is used to indicate that a local variable cannot be changed once its value is set;
  • It is used to indicate that a static variable cannot be changed once set, in effect implementing "constants";
  • It is used to indicate that a value of an instance variable cannot be changed once set; this makes accesses to that variable thread safe.

For Example

final double PI = 3.14;

PI = 1234; // does not compile

Example

public class FinalVariable

{

    final int a=10;

public void showValue()

      {

        System.out.println("Final variable value : "+a);

      }

public static void main(String[] args)

      {

        FinalVariable ob1=new FinalVariable();

        ob1.showValue();

      }

}

Output

variable.jpg
 

Final Class in Java

A Java class with the final modifier is called a final class in Java. Java classes that are declared as final cannot be extended, in other words inheritance is restricted. In other words a final class cannot be subclassed further. This is done for security and efficiency purposes.

It is used to indicate that a class cannot be extended. If a class is final then all of its methods are implicitly final as well, that is, the method is guaranteed not be overridden in any subclass. 

Syntax

public final class MyFinalClass

{

???..

.}

Basic Example

final class FinalClass

{

    public final int a;

    public final int b;

    MyFinalClass(int x, int y)

        {

           a = x;

           b = y;

        }

}

Example

class value

{

     int x, y;

}

class point extends value

{

     int a;

}

final class val extends point

{

     int z;

}

class FinalClass

{

   public static void main(String args[])

   {

         val Obj = new val();

         Obj.z = 10;

         Obj.a = 1;

         Obj.x = 5;

         Obj.y = 8;

         System.out.println("x = " + Obj.x);

         System.out.println("y = " + Obj.y);

         System.out.println("z = " + Obj.z);

         System.out.println("a = " + Obj.a);

   }

}

Output

class.jpg
 

Final Method in Java

The Final keyword in Java can also be applied to methods. A Java method with the final keyword is called a final method and it cannot be overridden in a sub-class. You should make a method final in Java if you think it's complete and its behavior should remain constant in sub-classes.

In methods private is equal to final, but in variables it is not.

Note : If we make a class both "private" and "final" then the "final" keyword is dismissed as a private method that cannot be accessed in its sub class. But you'll successfully be able to declare a method of the same name as in the base class if the method has been made private in the base class, then it doesn't mean you're overriding the method. You're simply declaring a new method in the sub class.

Note : You cannot make an "abstract" class or method as "final" because an "abstract" class needs to be extended that will not be possible if you make it "final".

Syntax

public class FinalMethod

{

  public final void myFinalMethod()

   {
 

   ???...

   ????

   }

}   

Example

class Method

{

        int a = 2;

        int b = 3;

        final void showValue() {

                System.out.println("First number value :" + a);

                System.out.println("Second number value :" + b);

        }

}

class Method1 extends Method

{

        /*It can not overridden. Because it is declared as final in super class.

         void showValue()

          {

          System.out.println("Final method can not overridden.");

          }

         */

}

 

public class FinalMethod

{

        public static void main(String[] arg0)

        {

                Method ob = new Method();

                ob.showValue();

        }

}

Output

method1.jpg
 

Advantages of Final Keyword in Java

  • Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently used final variables.
  • Final variables are safe to share in multithreading environments without additional synchronization overhead.
  • Final keyword allows JVM to optimize a method, variable or class.

Note : Final is different than the finally keyword that is used on an Exceptional Handling in Java and also final should not be confused with the "finalize()" method that is declared in the object class and called before an object is garbage collected by JVM.

 

Finally Keyword in Java

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block.

In Java, there are three clauses named try, catch and finally used as exception handler components. You use it in combination with "try" and "catch". Any commands after "finally" will be run whether there is an error or not. Cleanup commands are typically placed here.

  • The finally block always executes immediately after try-catch block exits.
  • The finally block is executed in case even if an unexpected exception occurs.
  • The runtime system always executes the code within the finally block regardless of what happens in the try block. So it is the ideal place to keep cleanup code.

Note : If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, then the finally block may not execute even though the application as a whole continues.

Importance of Finally Block

The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resources are always recovered.

Syntax

public void someMethod{

   Try
 

   {

   // some code

   }

   Catch(Exception x)
 

   {

   // some code

   }

   Catch(ExceptionClass y)
 

   {

   // some code

   }

   Finally

   {

   //this code will be executed whether or not an exception

   //is thrown or caught

   }

}

Example

public class FinallyBlock

{

    public static void main(String[] a)

    {

        /**

         * Exception will occur here, after catch block

         * the contol will goto finally block.

         */

        try

        {

            int i = 10/0;

        }

          catch(Exception ex)

        {

            System.out.println("Inside 1st catch Block");

        }

          finally

        {

            System.out.println("Inside 2st finally block");

        }

        try

        {

            int i = 10/10;

        }

          catch(Exception ex)

        {

            System.out.println("Inside 2nd catch Block");

        }

          finally

        {

            System.out.println("Inside 2nd finally Block");

        }

    }

}

Output 

finally.jpg
 

Finalize Method in Java

The Finalize() method is defined in the "java.lang.Object" class, which means it is available to all the classes for the purpose of overriding and its modifier is defined as protected. The finalize() method is not public because it should only be invoked by JVM and not by anyone else and protected so that it can be overridden by the subclasses.

Java uses a finalize method for garbage collection. Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before being collected.

The finalize() method is called before the Garbage collector reclaims the Object, it's the last chance for any object to perform the cleanup activity i.e. releasing any system resources held, closing the connection if open etc. The Finalize method in Java is a special method much like the main method in Java.

When not to use the finalize() method

1. The finalize method is not automatically chained like constructors. That means:

  • when you call a constructor then constructors of all super classes will be invoked implicitly. But, in case of finalize methods, this is not followed. The Super class's finalize() should be called explicitly.
  • If you are overriding the finalize method then it's your responsibility to call the finalize() method of the super-class, if you forgot to call it then the finalize of the super class will never be called. So it becomes critical to remember this and provide an opportunity to call finalize of the super class to perform cleanup. The best way to call the super class finalize method is to call them in a finally block.

2. The finalize method is called by the garbage collection thread before collecting the object and is not intended to be called like a normal method.

3. Finalize is to be called only once by the GC thread, if the object revives itself from the finalize method then finalize will not be called again.

4. Any Exception thrown by a finalize method is ignored by the GC thread and it will not be propagated further .

How to correctly use the Finalize() method

  • Always call "super.finalize()" in your finalize() method.
  • Do not use "Runtime.runFinalizersOnExit(true);" as it can put your system in danger.
  • We can run the finalize method by calling "System.runFinalization()" and "Runtime.getRuntime().runFinalization()". These methods ensure that the JVM calls the finalize() method of all objects eligible for garbage collection and whose finalize has not yet been called.

Finalize() Method declaration

protected void finalize() throws Throwable   

Example of how use the Finalize() method in Java

@Override

protected void finalize() throws Throwable

{

    try

    {

        System.out.println("Finalize of Sub Class");

        //release resources, perform cleanup ;

    }

    catch(Throwable t)

    {

        throw t;

    }

    finally

    {

        System.out.println("Calling finalize of Super Class");

        super.finalize();

     }

}

Difference between Final, Finally and Finalize in Java

Final

When a class is marked final, it cannot be subclassed.

When a method is marked final, it cannot be overridden by the subclass.

And when a field is marked final, its value, once set, cannot be reset or changed.

Finally

Finally is used in try-catch (i.e. exception handling in Java). Each try contains one and only one finally block. It is a block associated with the try catch; the main objective of a finally block is to maintain cleanup code that should execute always.

Finalize

It is a method should be executed by the "Garbage Collector" just before destroying an object. The main objective of a finalize method is to maintain cleanup code. Finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in a finalize() method before getting garbage collected.

Note : when compared with finalize, finally is always recommended to maintain cleanup code because there is no guarantee for the exact behavior of the "Garbage Collector"; it is Virtual Machine Dependent.

Up Next
    Ebook Download
    View all
    Learn
    View all