Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Final Keyword in Java

Have you ever wondered how to make your variables, methods, or even entire classes unchangeable in Java? The solution lies in a single keyword – the Final Keyword in Java. This versatile modifier plays a critical role in preventing modifications, ensuring stability, and securing your code from unwanted changes. 

In this blog, we'll dive deep into the multiple uses of the Final Keyword in Java. From locking down variables and methods to creating non-extendable classes, we'll explore how this keyword can make your programs more robust. Ready to learn more about how ‘final’ can safeguard your code? Let’s explore the magic behind this powerful keyword! 

Table of Contents 

1) What is the Final Keyword in Java? 

2) Key Features of the Final Keyword in Java 

3) Java Final Variable 

4) Java Final Method 

5) Java Final Class 

6) Advantages of Using the Final Keyword in Java 

7) Conclusion 

What is the Final Keyword in Java? 

In Java, the Final Keyword is used to ensure immutability and restrict modifications. It is applicable to classes, methods, and variables. This modifier is especially useful for enhancing security, improving performance, and ensuring the stability of core components in Java programs. 

The Final Keyword in Java can be used in many contexts. The ‘final’ can be: 

a) A `final` variable becomes a constant that cannot be changed once assigned 

b) A `final` method prevents overriding in subclasses, ensuring consistent behaviour 

c) A `final` class cannot be subclassed, safeguarding its functionality
 

Java Courses    

 

Key Features of the Final Keyword in Java 

Here are the key features of the Final Keyword in Java that make it essential for ensuring stability, security, and performance in your code: 

Key Features of the Final Keyword in Java 

a) Immutability: When a variable is declared as final, its value cannot be changed after it has been initialised.  

b) Prevention of Method Overriding: Declaring a method as final prevents subclasses from overriding it, ensuring consistent behaviour.  

c) Restricting Inheritance: Declaring a class as final prevents other classes from inheriting from it, which is essential when you want to secure core functionality. 

Master Java Swing Development Training to build dynamic, user-friendly desktop applications and elevate your software development skills today! 

1) Java Final Variable 

In Java, a final variable can only be initialised once, and after that, its value cannot be changed. This property makes final variables a good fit for constants in Java. You can declare final variables at class level (static final) or within methods (local final variables). 

Syntax:
 

final dataType variableName = value; 


Example of Java Final Variable 

Example:
 

public class FinalVariableExample { 

    public static final int MAX_SPEED = 120;  // Static final variable (constant) 

    public void displayMaxSpeed() { 

        final int speedLimit = 100;  // Local final variable 

        System.out.println("Speed Limit: " + speedLimit); 

    } 

    public static void main(String[] args) { 

        FinalVariableExample example = new FinalVariableExample(); 

        example.displayMaxSpeed(); 

        System.out.println("Max Speed: " + MAX_SPEED);  // Accessing the static final variable 

    } 


Output:

 

Speed Limit: 100 

Max Speed: 120 


1) Static Final Variable (MAX_SPEED): Declared as `public static final`, meaning it belongs to the class, is a constant, and can be accessed directly as `FinalVariableExample.MAX_SPEED`. Its value remains unchanged once initialised. 

2) Local Final Variable (speedLimit): Declared as `final` inside the `displayMaxSpeed()` method, meaning it cannot be modified after initialisation. It holds a constant value of 100 and is printed each time the method is called. 

3) Main Method: Creates an instance of `FinalVariableExample`, calls `displayMaxSpeed()` to print "Speed Limit: 100", and then prints the static final variable `MAX_SPEED` as "Max Speed: 120". 

Elevate your skills with our Web Development Using Java Training – register now and become a Java web expert! 

2) Java Final Method 

The final method in Java cannot be overridden by subclasses. This ensures that the specific method implementation remains unchanged in any derived class, providing stability in the behaviour of methods that must not be altered by subclassing. 

Syntax: 
 

final returnType methodName() { 

    // method body 


Example of Java Final Method 

Example: 

 

class Vehicle { 

    // final method 

    public final void run() { 

        System.out.println("The vehicle is running."); 

    } 

class Car extends Vehicle { 

    // This will cause an error if uncommented, as final methods cannot be overridden 

    // public void run() { 

    //     System.out.println("The car is running."); 

    // } 

    public void honk() { 

        System.out.println("The car is honking."); 

    } 

}

public class FinalMethodExample { 

    public static void main(String[] args) { 

        Car myCar = new Car(); 

        myCar.run();  // Calls the final method from Vehicle class 

        myCar.honk(); // Calls the Car's own method 

    } 



Output:

 

The vehicle is running. 

The car is honking. 


Explanation: 

a) The ‘run()’ method in the ‘Vehicle’ class is marked as ‘final’, which means that subclasses, such as ‘Car’, are not allowed to override it. 

b) Attempting to override the ‘run()’ method in the ‘Car’ class would result in a compilation error. 

c) In the ‘main’ method, when we create an instance of ‘Car’ and call ‘myCar.run()’, it will execute the ‘run()’ method from the ‘Vehicle’ class, as it cannot be overridden. 

Master Java EE Fundamentals with our comprehensive Introduction To Java EE Training Course and elevate your skills - join today!  

3) Java Final Class 

When a class is declared as final, it cannot be subclassed. This means no other class can inherit from a final class, making it useful in cases where you want to restrict inheritance for security or design reasons. 

Syntax:
 

final class ClassName { 

    // class body 


Example of Java Final Class 

Example:
 

// Final class definition 

final class Calculator { 

    public void add(int a, int b) { 

        System.out.println("Sum: " + (a + b)); 

    } 

// This will cause an error because Calculator is a final class 

// class AdvancedCalculator extends Calculator { 

//     public void multiply(int a, int b) { 

//         System.out.println("Product: " + (a * b)); 

//     } 

// }

public class FinalClassExample { 

    public static void main(String[] args) { 

        Calculator calc = new Calculator(); 

        calc.add(5, 10);   

    } 

}


Output:

 

Sum: 15 


Explanation: 

a) The ‘Calculator’ class is marked as ‘final’, which means no other class can extend it. If you try to create a subclass (e.g., ‘AdvancedCalculator’), it will result in a compilation error. 

b) The method ‘add()’ inside the ‘Calculator’ class can be used normally, but no new behaviour (such as overriding or additional methods) can be introduced through inheritance. 

Advance your career with our in-depth Java Courses – the ultimate step to becoming a sought-after Java Developer! 

Advantages of Using the Final Keyword in Java 

Here are the key advantages of using the Final Keyword in Java, which enhances the security, performance, and maintainability of your code: 

 

Advantages of Using the Final Keyword in Java 

a) Improved Performance: The Final Keyword can lead to performance optimisations. Since the value of a final variable doesn’t change, the Java compiler can make certain assumptions that result in more efficient code execution.  

b) Security: Declaring classes and methods as final provides a security mechanism by ensuring that sensitive methods cannot be overridden and that core functionality is preserved.  

d) Design Intent: Using the final clearly communicates to Java Developers that a class or method is intended to remain unchanged. It makes the code more readable and easier to maintain by preventing unnecessary or accidental modifications.  

e) Immutability: The Final Keyword helps create immutable objects in Java, which is a cornerstone of functional Programming and multi-threaded environments. Immutable objects can be shared safely between threads without the risk of data corruption.  

f) Thread Safety: Final fields make objects thread-safe by ensuring that their values remain consistent across different threads. This is particularly beneficial in concurrent programming. 

Achieve Java Engineering excellence and propel your career forward with our tailored Java Engineer Training - sign up now! 

Conclusion 

The Final Keyword in Java is a game-changer for Developers seeking to create stable, secure, and high-performance code. Locking down variables, methods, and classes brings both clarity and control to your programs. Embrace the power of ‘’final’ and elevate your Java Development! 

Elevate your career by mastering the Java Programming Course – join our course and become a coding expert! 

Frequently Asked Questions

What is the Effect of ‘final’ on a Method Parameter? faq-arrow

When a method parameter is declared as `final`, its value cannot be changed within the method. This ensures that the parameter remains constant throughout the method’s execution. 

Can You Use ‘final’ with Primitive Data Types? faq-arrow

Yes, you can use `final` with primitive data types. When a primitive variable is declared as `final`, its value cannot be changed after initialisation, making it a constant throughout the program. 

What are the Other Resources and Offers Provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide. 

Alongside our diverse Online Course Catalogue, encompassing 19 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA

What is The Knowledge Pass, and How Does it Work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds. 

What are the Related Courses and Blogs Provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including Java Programming, JavaScript for Beginners, Java Engineer Training and Web Development Using Java Training. These courses cater to different skill levels, providing comprehensive insights into Java Developer Job Description

Our Programming & DevOps Blogs cover a range of topics related to Java Programming, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming skills, The Knowledge Academy's diverse courses and informative blogs have got you covered. 

 

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SUMMER SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.