In Java, the words final, finally, and finalize are quite different from each other.
final is a keyword that is used to apply restrictions on a class, method, or variable.
When we try to modify the value of the final variable val
in the code below, it throws an error.
class HelloWorld {public static void main( String args[] ) {final int val=150;val=100;}}
In Java, finally is a block used to place important code that will be executed whether or not an exception is handled.
class HelloWorld {public static void main( String args[] ) {try{int val=150;}catch(Exception e){System.out.println(e);}finally{System.out.println("finally block!");}}}
finalize() is used to perform clean-up processing just before the object is collected by the garbage collector. In Java, the finalize method in a class is used for freeing up the heap’s memory, just like destructors in C++.
Note:
finalize
is deprecated in Java 9.
class HelloWorld {public static class test{int val = 50;@Overrideprotected void finalize() throws Throwable{System.out.println("Finalize Method");}}public static void main(String[] args){test a1 = new test();test a2 = new test();a1 = a2;// calling finalize methodSystem.gc();}}
Free Resources