Tuesday 22 November 2016

final keyword and its uses related to performance of the application

There many places in java final keyword is more useful.
  1. final variable and its static binding
  2. final method
  3. final class
1) final variable and its static binding
The value of the final variable cannot be changed once it is initialized.

     final int a=5;
     a=a++;      // compile time error

Once you have declared variable with final keyword, java compiler will identify this as final and replace it with actual value , this is called static time binding. This will improve the your application performance, i.e instead of reading every time from memory, it will replace variable name with its original value. For ex:
    
   final int a=5;
   int b=5;
   int add= a + b;
   int mul=a*b;
   int div=a/b;

The above source code will be converted into below code after compilation. 

   final int a=5;
   int b=5;
   int add= 5 + b;  
   int mul=5*b;
   int div=5/b;

The   java compiler replace the variable 'a' with its original value.
        
 In Real-time application, use final keyword before the  variable which is constant and doesn't change its value in entire flow of application, because it will improve the application performance.

2) final method

Final method cannot be overridden in sub class. You can use final keyword before the method, which you don't want to override in subclass. For ex:

Class Animal  {
   final public void getName() {
       System.out.println(" name ");
   }
}


Class Cat Animal {
   public void getName() {          // compile time error
       System.out.println(" name "); 
   }
}

3) final class
Final class cannot be extend in sub class.  In java, final keyword is used to create immutable class to avoid modification of those properties in sub class. All wrapper class such as Integer, Float , Double are created using final keyword.

final Class Immutable{
    // properties
}

Class Subclass extends Immutable {  // compile time error
}


Key points 
  1. if final variable is not initialized, it is called as blank variable and it will be initialized only in constructor.
  2. static blank final variable will be initialized only in static block.
  3. if you are using final variable in method arguments, it cannot be changed inside the method.
  4. constructor cannot be final.
  5. final method can be inherited but it cannot be override.
  6. All variable declared inside java interface are implicitly final





If you like the above solution . Please share this blog




No comments:

Post a Comment

s