Categories: Core JAVATutorial

final keyword in Java

The final is a keyword. This is similar to const keyword in other languages. This keyword may not be used as identifiers i.e. you cannot declare a variable or class with this name in your Java program.

The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:

  1. variable
  2. method
  3. class

The final keyword can be applied with the variables, that have no value it is called blank final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let’s first learn the basics of final keyword.

1. final variable: A final variable can only once assigned a value. This value cannot be changed latter. If final variable used in class then it must assigned a value in class constructor. Attempting to change the value of final variable/field will generate error.

Unlike the constant value, the value of a final variable is not necessarily known at compile time. Final variable comes in mostly two important situations: to prevent accidental changes to method parameters, and with variables accessed by anonymous classes.

The syntax of declaring a final type variable is:

public final double radius = 126.45;
public final int PI = 3.145;

Example of final variable:

There is a final variable speedlimit, we are going to change the value of this variable, but It can’t be changed because final variable once assigned a value can never be changed.

class Bike{
  final int speedlimit=90;//final variable
  
  void run(){
   speedlimit=400;
  }

  public static void main(String args[]){
  Bike obj=new  Bike();
  obj.run();
  }
}


Output:
Compile Time Error

2. final method:
A final method cannot be overridden by subclasses and not be hidden. This technology prevents unexpected behavior from a subclass for altering a method that may be crucial to the function of the class.

Note: private and static methods are always implicitly final in Java, since they cannot be overridden.

The syntax of declaring a final type method is:

public class MyFinalClass {

  public final void myFinalMethod()
   { 
    //code here
  }
}    

Example of final method:

class Bike{
  final void run()
   {
    System.out.println("running");
   }
}
   
class Honda extends Bike{
   void run()
    {
       System.out.println("running safely below 100kmph");
    }
   
   public static void main(String args[]){
     Honda honda = new Honda();
     honda.run();
   }
}   


Output:
Compile Time Error

3. final class:
A final class cannot be extended. A final class implicitly has all the methods declared as final, but not necessarily the data members.

The syntax of declaring a final type method is:

public final class MyFinalClass {

//code here

} 

Example of final class:

final class Bike{}
 
 class Honda extends Bike{
   void run(){
   System.out.println("running safely below 100kmph");
   }
   
   public static void main(String args[]){
      Honda honda= new Honda();
      honda.run();
   }
}


Output:
Compile Time Error


Is final method inherited?

Yes, final method is inherited but you cannot override it.
For Example:

class Bike{
  final void run(){
    System.out.println("running...");}
  }
class Honda extends Bike{
   
   public static void main(String args[]){
    new Honda().run();
   }
}


Output:
running…

What is blank final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor.

class Employee{
int empId;
String empName;
final String PAN_CARD_NUMBER;
...
}

Can we initialize blank final variable?
Yes, but only in constructor.
For example:

class Employee{
int empId;
String empName;
final String PAN_CARD_NUMBER;
Employee(){
  PAN_CARD_NUMBER = "CSA122ASS";
  System.out.println(PAN_CARD_NUMBER);
  }

  public Static void main(String args[]){
    new Employee();
 }
}


Output:
CSA122ASS

static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

class A{
  static final int data;//static blank final variable
  
  static{ 
   data=50;
  }

  public Static void main(String args[]){
    System.out.println(A.data);
 }
}

What is final parameter?
If you declare any parameter as final, you cannot change the value of it.

class Bike{
  int cube(final int n){
   n=n+2;//can't be changed as n is final
   n*n*n;
  }


  public Static void main(String args[]){
    Bike b=new Bike();
    b.cube(5);
 }
}


Output:
Compile Time Error

  • A java variable can be declared using the keyword final. Then the final variable can be assigned only once.
  • A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialize it.
  • Java classes declared as final cannot be extended. Restricting inheritance!
  • Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not.
  • final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding.
  • Java local classes can only reference local variables and parameters that are declared as final.
  • A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago