Final Keyword in Java

Introduction to Final Keyword in Java

The `final` keyword in Java is used to declare constants, methods, and classes as final. This means that once they are initialized, they cannot be changed.

Final constants are useful for defining values that should not change throughout the program, such as mathematical constants or configuration settings. Final methods are useful for preventing subclasses from overriding methods in the superclass. Final classes cannot be extended by other classes.

Here is an example of how to use the `final` keyword:

public final class MyClass {
  public static final int MY_CONSTANT = 10;

  public final void myMethod() {
    // ...
  }
}

In this example, the `MY_CONSTANT` variable is a final constant, so it cannot be changed once it is initialized. The `myMethod()` method is a final method, so it cannot be overridden by subclasses of the `MyClass` class. The `MyClass` class is a final class, so it cannot be extended by other classes.

Using the `final` keyword can have a number of benefits, including:

  • Improved readability and maintainability: By using the `final` keyword, you can make your code more readable and maintainable by making it clear which values and methods cannot be changed.
  • Reduced errors: The `final` keyword can help to reduce errors in your code by preventing accidental changes to constants, methods, and classes.
  • Improved performance: In some cases, the compiler can optimize code that uses the `final` keyword.

Overall, the `final` keyword is a powerful tool that can help you to write more robust, efficient, and maintainable Java code.

Here are some additional tips for using the `final` keyword effectively:

  • Use the `final` keyword for constants, methods, and classes that should not change throughout the program.
  • Be careful not to overuse the `final` keyword, as this can make your code less flexible.
  • Document the reasons for using the `final` keyword in your code.

If you are working with Java, I encourage you to learn more about the `final` keyword and how to use it effectively.

Exercises

Code for declaring and initializing a Final Variable


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
  public static void main(String args[])
    {
    student satish = new student();
    satish.display_student();
  }
  }
  
  class student
  {
    //declaring a final variable
  public final String university="vit university";
  
  public void display_student() {
    System.out.println(university);		
  }
  } 

Code for Initializing a final variable inside constructor


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
  public static void main(String args[])
  {
    student satish = new student();
    satish.display_student();
  }
  }
  
  class student
  {
  public final String university;
  
  public student() {
    //initialization allowed only within a constructor
    university = "vit university";
  }
  
  public void display_student() {
    System.out.println(university);		
  }
  } 

Code to demonstrate the Inheritance of a final variable


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
    public static void main(String args[])
      {
      btechstudent satish = new btechstudent();
      satish.display_btech();
      }
  }
  class student
  {
    protected final String university;
    
    public student() {
      //initialization allowed only within a constructor
      university = "vit university";
    }
    
    public void display_student() {
      System.out.println(university);		
    }
  }
  
  class btechstudent extends student
  {
    public void display_btech()
    {
      System.out.println(this.university);
    }
  } 

Demo Code for declaring final and static variable


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
    public static void main(String args[])
      {
      btechstudent satish = new btechstudent("123");
      satish.display_student();
      btechstudent.display_credits();
      }
  }
  class student
  {
    protected final String university;
    
    public student() {
      //initialization allowed only within a constructor
      university = "vit university";
    }
    
    public void display_university() {
      System.out.println(university);		
    }
  }
  
  class btechstudent extends student
  {
    final String regno;
    //declaration of a static final variable is given below
    static final int creditsRequired = 160; 
    public btechstudent(String regno) {
      this.regno=regno;
    }
    
    public void display_student()
    {
      System.out.println(this.regno);
    }
    
    public static void display_credits()
    {
      System.out.println(btechstudent.creditsRequired);
    }
  } 

Code for demonstrating that final methods are inherited but cannot be overridden


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
    public static void main(String args[])
      {
      btechstudent satish = new btechstudent("123");
      //shows final method being inherited
      satish.display_university();
      }
  }
  class student
  {
    protected final String university;
    
    public student() {
      //initialization allowed only within a constructor
      university = "vit university";
    }
    
    protected final void display_university() {
      System.out.println(university);		
    }
  }
  
  class btechstudent extends student
  {
    final String regno;
    static final int creditsRequired = 160; 
    public btechstudent(String regno) {
      this.regno=regno;
    }
    
    public void display_student()
    {
      System.out.println(this.regno);
    }
  
    //!!!! overriding a final method as shown below will lead to error.
    //uncomment the code and test it for yourself.
    /*protected final void display_university() {
      System.out.println(university);		
    }*/
  
    public static void display_credits()
    {
      System.out.println(btechstudent.creditsRequired);
    }
  } 

Demo code for initializing a final variable inside a static block .


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
    public static void main(String args[])
      {
      btechstudent satish = new btechstudent("123");
      //shows final method being inherited
      satish.display_university();
      }
  }
  class student
  {
    protected final String university;
    
    public student() {
      university = "vit university";
    }
    
    protected final void display_university() {
      System.out.println(university);		
    }
  }
  
  class btechstudent extends student
  {
    final String regno;
    static final int creditsRequired;
    static
    {
      creditsRequired=160;
    }
    public btechstudent(String regno) {
      this.regno=regno;
    }
    
    public void display_student()
    {
      System.out.println(this.regno);
    }
    
    public static void display_credits()
    {
      System.out.println(btechstudent.creditsRequired);
    }
  } 

Demo code that shows final classes cannot be inherited - This code will lead to errors as we are trying to inherit a class declared as final


  package javaprogrammingdemo;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
  import java.io.Serializable;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
          
      btechstudent satish = new btechstudent("123");
      //shows final method being inherited
      satish.display_university();
      }
  }
  final class student
  {
    protected final String university;
    
    public student() {
      //initialization allowed only within a constructor
      university = "vit university";
    }
    
    protected final void display_university() {
      System.out.println(university);		
    }
  }
          
  //this code will lead to an error in the line given below.
  //final classes cannot be inherited
  class btechstudent extends student
  {
    final String regno;
    static final int creditsRequired = 160; 
    public btechstudent(String regno) {
      this.regno=regno;
    }
    
    public void display_student()
    {
      System.out.println(this.regno);
    }
  } 

Demo code for final arrays in Java


  package javalabdemo;
  import java.util.*;
  public class javalabclass 
  {
    public static void main(String args[])
      {
      //reference cannot be reassigned
      final int a[]=new int[5];
        for(int i=0;i<a.length;i++)
      {
        a[i]=i;
      }
      for(int i=0;i<a.length;i++)
      {
        a[i]=i+1;
      }
      for(int k:a)
      {
        System.out.println(k);
      }
    }
  }