The difference between final, finally, and finalize in Java
In Java, the words final, finally, and finalize are quite different from each other.
final
final is a keyword that is used to apply restrictions on a class, method, or variable.
- The class with this keyword cannot be inherited.
- The method with this keyword cannot be overridden.
- The variable with this keyword cannot be changed.
Code
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;}}
finally
In Java, finally is a block used to place important code that will be executed whether or not an exception is handled.
Code
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
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:
finalizeis deprecated in Java 9.
Code
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
Copyright ©2025 Educative, Inc. All rights reserved