final keyword

Basically final keyword can be used in three ways. In classes, in methods and in variables. Let’s see how and why final keyword used in these three places.

In Variables

If you use finally keyword in variables, it just simply means that variable is no longer a variable, it is constant now. So you can’t change that.

final string STRING_CONSTANT="this is a constant";


In a Class

Classes with finally keyword can’t extend anymore. You can just, make instances of that class, but you can’t extend that and create a new class.

final class ClassA{

//class body here


In a method

If you use finally keyword with methods, those methods can’t override in the extended classes. But you can still use them in extended classes.

final void doSomething(){

//method body here


finally keyword

This keyword is used with try block. What this keyword (the finally block) do is even after an unexpected exception occur in try block, this block always execute.


//things to execute in try block

}catch(Exception ex){

//things to do when exception occurs


//this block will always execute anyway