Wednesday, 19 August 2015

final, finally and finalize

final keyword
final is used to apply restrictions on class, method and variable.
final class can't be inherited.
final method can't be overridden.
final variable value can't be changed.
class FinalExample { 
       public static void main(String[] args){ 
           final int x=100; 
           x=200;// Compile Time Error-The final local variable x cannot
                 // be assigned. It must be blank and not using a compound
                 // assignment

finally block
Finally is used to place important code, it will be executed whether exception is handled or not.
class FinallyExample{ 
       public static void main(String[] args){ 
              try {
                     int a = 0;
                     int b = 300;
                     int c = b/a;
                     System.out.println("result :" + c);
              } catch(Exception e) {
              } finally {
                     System.out.println("finally block is executed");
java.lang.ArithmeticException: / by zero
finally block is executed

finalize() method
Finalize is used to perform clean up processing just before object is garbage collected.

class FinalizeExample{
       public void finalize() {
              System.out.println("finalize called");
       public static void main(String[] args) {
              FinalizeExample f1 = new FinalizeExample();
              FinalizeExample f2 = new FinalizeExample();
              f1 = null;
              f2 = null;
finalize called
finalize called

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...