Final Keyword in java - rahul00773/JavaConcepts GitHub Wiki

Only the applicable modifier for the local variable is final. By Default its not final but we can declare it as final using the final keyword. By mistake, if we are trying to apply any other modifier then we will get compile-time error.

We can not declare local variables as static, private, protected.

Final

Final is a modifier applicable for classes, Methods, and Variables. If a class declared as final then we can't extend that class. That is we can't create child class for that class. That is inheritance is not possible for final classes.

If a Method is final then we can't override that method in the child class.

If a variable declared as final then we can't perform reassignment for that variable.

Finally:

Finally is a block always associated with try-catch to maintain clean up code.

try{

"risky code"

}
catch (Exception e){ "Handling code" } finally{ "clean up code" }

The specialty of the finally block is it will be executed always irrespective of whether an exception is raised or not raised. And whether handled or not handled.

Finallize:

Finalize is a method always invoked by garbage collector just before destroying an object to perform clean up activities. Once the finalize method completes immediately garbage collector destroys that object.

Note:

Finally, the block is responsible to perform clean up activities related to trying block. That is whatever resources we opened as the part of try block will be closed inside finally block.

Whereas the finalize method is responsible to perform clean up activities related to the object. That is whatever resources associated with the object will be deallocated before destroying an object by using the finalize method

  • In try-catch-finally, the order is important
  • whenever we are writing try compulsory we should write either catch of finally. Otherwise, we will get compile-time error. That is "try" without a catch or finally is invalid.
  • Whenever we are writing a catch block compulsory try is required.
  • Whenever we are writing the finally block compulsory we should write try block. That is finally without try is invalid.
  • Inside try-catch and finally block we can declare try,catch, and finally block. That is nesting of try-catch-finally is allowed.
  • For Try catch and finally block curly braces are mandatory.