Answers

Question and Answer:

  Home  Sr.Java Web Developer

⟩ Please explain what purpose does the keywords final, finally, and finalize fulfill?

Final:

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. Let’s take a look at the example below to understand it better.

class FinalVarExample {

public static void main( String args[])

{

final int a=10; // Final variable

a=50; //Error as value can't be changed

}

Finally

Finally is used to place important code, it will be executed whether exception is handled or not. Let’s take a look at the example below to understand it better.

class FinallyExample {

public static void main(String args[]){

try {

int x=100;

}

catch(Exception e) {

System.out.println(e);

}

finally {

System.out.println("finally block is executing");}

}}

}

Finalize

Finalize is used to perform clean up processing just before object is garbage collected. Let’s take a look at the example below to understand it better.

class FinalizeExample {

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();

}

}

 175 views

More Questions for you: