DEV Community

Mukesh
Mukesh

Posted on

Mastering final Keyword in Java: Variables, Methods & Classes Explained

Understanding the final Keyword in Java

In Java, the final keyword is powerful tool used to restrict modification. Whether applied to variables, methods, or classes, final enforces immutability and prevents unexpected behavior, making your code more robust and secure.

In this blog, will break down how final keyword works in Java covering final variables, final methods, and final classes along with examples.

What Does final Do?

final keyword can be used in three main contexts:

  1. Final variables
  2. Final methods
  3. Final classes

1. Final Variables

When variable is declared as final, its value cannot be changed once initialized. Trying to reassign final variable will result in compile-time error.

Example:

final int x = 10; x = 20; // Compile Time Error: cannot assign value to final variable 
Enter fullscreen mode Exit fullscreen mode

Blank Final Variable

You can declare a final variable without assigning value this is called a blank final variable. It must be initialized either in the constructor or during object creation.

class A { final int speed; A() { speed = 100; // Initialized in constructor } } 
Enter fullscreen mode Exit fullscreen mode

Static Blank Final Variable

static final variable that isn’t initialized during declaration is known as static blank final variable. It must be initialized 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); } } 
Enter fullscreen mode Exit fullscreen mode

2. Final Methods

When a method is declared as final, it cannot be overridden by any subclass. This is especially useful when you want to prevent modification of critical functionality.

class Bike { final void run() { System.out.println("Running..."); } } class Honda extends Bike { // void run() { System.out.println("Running safely"); } // Compile Time Error } 
Enter fullscreen mode Exit fullscreen mode

3. Final Classes

If class is declared as final, it cannot be extended. This is often done for security or to prevent alteration of core behavior.

final class Vehicle { void start() { System.out.println("Vehicle started"); } } // class Car extends Vehicle {} // Compile Time Error 
Enter fullscreen mode Exit fullscreen mode

Conclusion

final keyword helps enforce immutability, security, and clarity in Java code. Whether you are preventing variables from being modified, methods from being overridden, or classes from being extended, final plays a crucial role in writing clean, error-free code.

Top comments (0)