Difference between final, finally and finalize

Difference between final, finally and finalize

Difference between final, finally and finalize

Difference between final, finally and finalize:

final, finally, and finalize are three keywords in Java that are used in different contexts and have different meanings.

  1. final: final is a keyword used to define constants, which cannot be modified once they are initialized. A final class cannot be subclassed, a final method cannot be overridden, and a final variable cannot be reassigned. final is often used to define values that should not be changed, such as mathematical constants or configuration parameters. For example:
				
					javaCopy code
final int MAX_VALUE = 100; final String SERVER_ADDRESS = "example.com"; final MyClass obj = new MyClass(); // obj cannot be reassigned 

				
			
  1. finally: finally is a keyword used in a try-catch block to specify a block of code that will be executed regardless of whether an exception is thrown or not. Thefinally block is optional, but if it is included, it will be executed even if an exception is thrown and not caught. The finally block is often used to release resources that were acquired in the try block, such as file handles or database connections. For example:
				
					final int MAX_VALUE = 100;
final String SERVER_ADDRESS = "example.com";
final MyClass obj = new MyClass(); // obj cannot be reassigned

				
			

 

  1. finalize: finalize is a method in the Object class that is called by the garbage collector when an object is about to be garbage collected. finalize can be overridden in a class to perform cleanup operations before an object is garbage collected. However, it is generally recommended to avoid using finalize and instead use try-with-resources or other cleanup mechanisms to release resources in a timely manner. For example:
				
					protected void finalize() throws Throwable {
    // code to perform cleanup operations before the object is garbage collected
super.finalize();
}

				
			

In summary, final is used to define constants that cannot be modified, finally is used to specify a block of code that will be executed regardless of whether an exception is thrown or not, and finalize is a method that is called by the garbage collector before an object is garbage collected.

 

 

Join To Get Our Newsletter
Spread the love