Asked

What is the difference between finally and finalize() in Java?

Kaushik

The two Java functions “finally” and “finalize()” are often confused by Java developers due to their similar sounding names, but they are very different. For example, the “finally” block is used for the prevention of any kind of exception. finally is a block of code which is executed when the “try” code ends, which means that the finally block will get executed forcibly.

It also forces the execution of cleanup codes, as sometimes they are skipped due to certain functions such as “break”, “return” or “continue”.  An example of a finally block is given below:

Class FinallyEg{

Public static void main(String[]args){

try{

int x=30;

}catch(Exception ex){System.out.printIn(ex);}

Finally{System.out.printIn(“finally block is executed”);}

}}

On the other hand, “finalize” is called when the object is garbage collected. The system resources release code can be written according to this method for more efficient garbage collection. An example of finalize() code is given below -

class FinalizeEg{

public void finalize()

{

System.out.println("finalize is called");

}

public static void main(String[] args){

FinalizeExample F1=new FinalizeExample();

FinalizeExample F2=new FinalizeExample();

F1=null;

F2=null;

System.gc();

}}

There is another similar sounding term in Java, which also baffles developers. This is the “final” function, which is actually a keyword which instructs the runtime to make a variable, method or class final. A variable affected by the “final” keyword cannot be changed, a final method cannot be overridden and no objects can be added to a final class. Here is a small example of the “final” keyword.

class FinalEg{

public static void main(String[] args){

final int a=10;

a=20; //Will give compile time error

}}

Feeds
Feeds
Latest Questions
Top Writers