P. 1


|Views: 1|Likes:
Final keyword in Java
Final keyword in Java

More info:

Published by: Aravindhan Ragunathan on Aug 04, 2013
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





What is the difference between final, finally and finalize in Java?

final - final is a keyword in Java used to indicate whether variable, method or class can be a final. Once a variable set as final then the value can't be changed. Once a method set as final then the method can't be override d. Once a class set as final then the class can't be inherited or extended by other classes. finally - finally is block used in exception handling. Finally can be followed by try-catch or without catch block. But once we place a finally block then it will be executed always. finalize - finalize is a method and used in garbage collection. finalize() method will be invoked just before the Object is garbage collected. It will be called automatically by the JVM on the basis of resource reallocating. Even programmers can call finalize method by using System.gc(); but vendor to vendor (Different OS) will change and not sure 100% finalize method will be called. Lets see small program for final, finally and finalize

Example for final:
// Final class public final class FinalTest { // Final member variable private final int id = 100; // Final method public final void getValue(){ System.out.println("Inside final method"); } }

out.Example for finally: public final class FinallyTest { public int getValue1(){ try{ return 10. System.println("VALUE-2 : "+val2). }finally{ return 20. int val2 = obj. int val1 = obj. System.getValue2().getValue1().printStackTrace(). } } Example for finalize: public final class FinalizeTest { @Override . } } public static void main(String[] args) { FinallyTest obj = new FinallyTest(). }finally{ return 200. } } public int getValue2(){ try{ return 100.out. }catch(NumberFormatException e){ e.println("VALUE-1 : "+val1).

gc().printStackTrace(). } public static void main(String[] args) { try{ FinalizeTest obj = new FinalizeTest(). super. }catch (Exception e) { e.finalize(). } System.println("Inside Finalize method"). } } .out.protected void finalize() throws Throwable { System.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->