Friday, December 30, 2011

Java final keyword

final (keyword)


In Java, final keyword is applied in various contexts.
1. If class is marked as final that class cannot be inherited

2. If method is marked as final that method cannot be overridden

3. If the variable is declared as final then the value can’t be changed or reassigned

4. If the Arguments of a method declared as final those variables cannot be modified within the method.

                                  final int i=10;

The variable i declared as final only once we can assign the value. If try to modify it leads to the compilation error.

                                  final int var;


The final variables won’t be initialized with default values by JVM. It’s compulsory we should perform initialization before compilation of the constructor.

/* Program to demonstrate the blank final variables */

package com.jsl.core.book;
public class FinalKeywordExample {

 final int var; // Blank final variables.

 public FinalKeywordExample() {

  var = 100;
 }

 public void display( ){
     
  System.out.print(“The value of final variable is :”+var); 
        }
}
/* Program to demonstrate the final local variables */

package com.jsl.core.book;
import java.util.Scanner;

public class FinalKeywordExample {

public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the no : ");
  int no = sc.nextInt();
  double res = factorialOfNumber(no);
  System.out.println("The factorial of : " + res);
 }

 private static double factorialOfNumber(final double no) {

  double res = 1;
  for (int i = 1; i <= no; i++)
   res = res * i;
  return res;
 }
}

The static final variable must be initialized when it is declared or must be initialized inside the static block.

/* Program to demonstrate the static final variables */

package com.jsl.core.book;
public class FinalKeywordExample {
        
                       private final static int var1=5;
                       private final static int var2; // Blank static final variable. 

                       static{
                                     var2=10;
                        }

public static void main(String[] args) {
             
                         System.out.println("The product of "+var1+" and "+var2+" = "+(var1*var2));
              }
}

If the final variable is declared inside the method that variable must be initialized before using, otherwise its leads to the compilation error.

public void showNumber( ){

                        final int no;
                        System.out.print(“The value of no is : “+no)
                       //Its leads to the compilation error. The local variable no must be initilzed before using.
}

/* Program to demonstrate final local variables */

package com.jsl.core.book;
public class FinalKeywordExample {

            public static void showNumber(){

                               final int no=100;
                               System.out.println("The value of no is : "+no);
}

public static void main(String[] args) {
             
                             showNumber();
             }
}

final methods:

The final keyword prevents a method from being overridden in a subclass, normally if methods, not necessary to change the functionality, then those methods can be marked as final.


public final void getSimpleInterest( ){
            
                          body
                           -----------------

}

/* program to demonstrate the final methods */

package com.jsl.core.book;
public class FinalKeywordExample {

              public final static double calSimpleInterest(double p,double t,double r){
              
                             return (p*t*r)/100;
              }
}

/* Main class to access the methods */

package com.jsl.core.book;
public class MainClass {

public static void main(String[] args) {
                   
                           Double interest=FinalKeywordExample.calSimpleInterest(100000, 12, 1);
                           System.out.println("The interest is : "+interest);
         }
}

final reference variable:

final reference variables cannot refer to a different object once the object has been assigned to the final variable. final reference variables must be initialized before the constructor completes.

There is no such thing as a final object. An object reference marked final does not mean the object itself is immutable. That object allows you to make the modification and behaves like a mutable object.


/* program to demonstrate the final reference variables */ 

package com.jsl.core.book;
public class MainClass {
                   
                   public static void main(String[] args) {
                   final String fname=new String("Lakshman");
                   fname=new String("JSLTech");
                  // Leads compilation error. The final reference variable can be assigned only once.
            }
}

final classes:

A final class cannot be sub classed i.e. that classes can’t be inherited. If classes is declared as final then all that class methods behave like final methods.

/* Program to demonstrate the final classes */

package com.jsl.core.book;
          
          public final class FinalKeywordExample {
          private FinalKeywordExample(){
}
public static double calSimpleInterest(double p,double t,double r){
            
           return (p*t*r)/100;
}
public static double currencyConversion(final int amount,final int price){
              
           return amount*price;
      }
} 
/* Main class to access the final class methods */

package com.jsl.core.book;
public class MainClass {

                public static void main(String[] args) {
                System.out.println(FinalKeywordExample.calSimpleInterest(100000,10, 1.50));
                System.out.println(FinalKeywordExample.currencyConversion(5000,68));
       }
}

1 comment:

  1. Nice post just to add while using blank final variable , they have to be initialized on all constructor either explicitly or via constructor chaining or else compiler will complain that final variable might not be initialized. I have also shared few pointers on final keyword in Java, you may find useful.

    Thanks
    Javin

    ReplyDelete

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...