Friday 9 February 2018

final, finally and finalize in Java


final
final is a keyword.

final is a  keyword which is used in variable, method and class.

If a variable is declared as final then we cannot change the value, once it is initialized.
In other words the variable is constant.


If a method is declared as final then we cannot write the same method again and again

In other words final method can not be overridden.


If a class is declared as final then we cannot extends new class from final class.

In other words final class cannot be inherited.

Example:

public class DemoFinal{

 final int x=50; //final variable

 void display()

{

  x=78;

  System.out.println("x is:"+x);

 }

 public static void main(String args[]){

  DemoFinal df=new   DemoFinal();

 df.display();

 }


}

 Output:

 Compile time error

 finally
finally is a block. The finally block always executes when the try block exits.
 finally is used to execute important code whether exception is handled or not.


finally is used in exception handling mechanism.The finally block is optional in try-catch block.


finally block is to close the resources or clean up objects.For e.g.Closing a FileStream,


Example:
public class DemoFinally{ 
  public static void main(String args[]){ 
   try{ 
      int x=50/0; 
       System.out.println(x);
     }
    
   catch(ArithmeticException ae)
   {
       System.out.println(ae);
      
   } 
   finally{
   System.out.println("Close the operation"); 
     }
} 
}
Output:
java.lang.ArithmeticException: / by zero
Close the operation.

finalize
finalize is a method.
finalize method is called before garbage collector for clean up the memory.
finalize is called by system.gc() where gc is garbage collector method.

Example:
public class DemoFinalize{ 
public void finalize()
{
System.out.println("finalize demo");
  } 
public static void main(String[] args){ 
 DemoFinalize f1=new  DemoFinalize(); 
f1=null;
System.gc(); 
}
} 
Output:
finalize demo

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...