Java Made Clear: Difference final vs finally Keyword

For a Novice, both final and finally look similar but are very different like throws and throw in threads. Let us see when to use them with examples in simple terms final vs finally.

final vs finally: I. Usage of final Keyword

Unlike other keywords of Java, final can be used in three places and gives different meanings in each place.

final keyword usage:

a) Can be used with variables (gives the meaning of constant)
b) Can be used with methods (gives the meaning of cannot be overridden)
c) Can be used with classes (gives the meaning of cannot be extended)

final vs finally: a) "final" Keyword usage with Variables

Java does not support "const" keyword of C/C++. In its place, Java uses final keyword. That is, a final variable cannot be reassigned. Observe the following example on final vs finally.

public class Demo
{
  public static void main(String args[])
  {
    int cost = 10;		          // observe, cost is not final and can be reassigned
    System.out.println("Non-final cost before reassignment: " + cost);        // prints 10
    cost = 20;		                  // now reassigned
    System.out.println("Non-final cost after reassignment: " + cost);         // prints 20

    final int price = 100;		 // observe, price is final and cannot be reassigned
    System.out.println("final price: " + price);	                      // prints 100
    // price = 200;		         // raises error as price is declared as final
  }
}

final vs finally

final vs finally: b) "final" Keyword usage with Methods

In a super class if a method is declared as final, the subclass cannot override it. But remember, as usual, the non-final methods can be overridden at the choice of subclass. See the following code of final vs finally.

class Test
{
  public final void display()             	// observe, display() is final and cannot be overridden
  {
    System.out.println("From super class display() method");
  }
  public void show()             	        // observe, show() is not-final and can be overridden
  {
    System.out.println("From super class show() method");
  }
}
public class Demo extends Test
{
  // public final void display()  {   }         // error as display() is final in super class
  public void show()             	        // observe, show() is overridden here as it is not final in super class
  {
    System.out.println("From subclass show() method");
  }
  public static void main(String args[])
  {
    Test t1 = new Test();              
    d1.display(); 
    d1.show();
  }
}

final vs finally

final display() of super class Test cannot be overridden by subclass Demo; observe, it is commented in subclass. As show() in super class is not final, it is overridden by subclass happily.

final vs finally: c) "final" Keyword usage with Classes

Java supports multilevel inheritance. Any class can extend another class to inherit other class properties. But sometimes, a class would like not to permit other classes to extend it. Then, it declares its class simply as "final". That is, a final class can be extended or inherited by other classes. See the code how to use final keyword with classes.

final class Test               // observe, the Test class is declared as final
{
  public void display()
  {
    System.out.println("From final super class Test display() method");
  }
}
public class Demo              // extends Test
{			       // if Test is extended, it gives error
  public static void main(String args[])
  {
    Test t1 = new Test();      // composition
    t1.display(); 
  }
}

final vs finally

Observe, Test is declared as final. So, Demo cannot extend it. Then, how Demo can make use of Test class method display()? By creating Test class object, t1, and calling with t1. It is known as composition. Note that, Demo object cannot call display().

final vs finally: II. Usage of finally Keyword

finally keyword is used, in exception handling, in combination with try-catch mechanism. finally block statements are guaranteed of execution even if the catch block fails to handle the exception thrown by try block. Observe the code.

public class Demo
{		
  public static void main(String args[])
  {
    try
    {
      System.out.println(10/0);             // throws ArithmeticException
    }
    catch(NumberFormatException e)          // wrong handler, does not catch and whole block is not executed
    {
      System.out.println("From catch block, it is not executed. " + e);
    }    
    finally                                 // definitely executed
    {
      System.out.println("From finally block, it is executed");
    }
    System.out.println("Not executed as ArithmeticException is not handled");   
  }
}

final vs finally

The try block throws ArithmeticException and catch block is unable to handle it due to wrong handler NumberFormatException. But finally block statement is executed as it is guaranteed of execution whether the catch block handles the exception successfully or not. finally block is used by Programmer to close the file streams, close socket handles or JDBC connections etc. which are required definite execution.

1. Can we use finally with try but without catch?
2. Also know the difference between final-finally-finalize in Java.

Leave a Comment

Your email address will not be published.