Difference between final, finally and finalize
Difference between final, finally and finalize in Java
The main difference between final, finally and finalize is; Final is a keyword, Finally is a block and Finalize is a method.
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed. In single word final is a keyword which is used to make a variable or a method or a class as unchangeable.
finally is a block which is used for exception handling along with try and catch blocks. It is used to place important code, it will be executed whether exception is handled or not.
finalize() method is a protected method of java.lang.Object class. Finalize is used to perform clean up processing just before object is garbage collected.
Example of Final keyword in Java
final can be used to mark a variable "unchangeable"
Example
private final String name = "foo"; //the reference name can never change
final can also make a method not "overrideable"
Example
public final String toString() { return "NULL"; }
final can also make a class not "inheritable". i.e. the class can not be subclassed.
Example
public final class finalClass {...} public class classNotAllowed extends finalClass {...} // Not allowed
Example
class FinalExample{ public static void main(String[] args) { final int no=10; no=20; //Compile Time Error we can't change final variable value } }
Example of Finally keyword in Java
finally is used in a try/catch statement to execute code always
Example
lock.lock(); try { //do stuff } catch (SomeException se) { //handle se } finally { lock.unlock(); //always executed, even if Exception or Error or se }
Example
class FinallyExample { public static void main(String[] args) { try { int x=300; }catch(Exception e) { System.out.println(e); } finally{System.out.println("finally block is executed"); } } }
Example of Finalize keyword in Java
finalize is called when an object is garbage collected. You rarely need to override it.
Example
protected void finalize() { //free resources (e.g. unallocate memory) super.finalize(); }
Example
class FinalizeExample { public void finalize() { System.out.println("finalize called"); } public static void main(String[] args) { FinalizeExample f1=new FinalizeExample(); FinalizeExample f2=new FinalizeExample(); f1=null; f2=null; System.gc(); } }