Sunday, August 22, 2021

What is final in Java? Final variable , Method and Class Example

Final in Java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is a final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase the performance of Java application.

Example of Final variable, Final method, and Class in Java

Now, let's understand the final keyword in detail in Java. We will start with final variable then explore final methods and finally the final class in Java. After going through these examples, you will learn the impact of making a variable, method, or a class final in Java. 


1. What is a final keyword in Java?

Final keyword, final variable, final method and class in java exampleFinal is a keyword or reserved word in Java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise a compilation error if you try to re-initialized final variables in Java.



2. What is the final variable in Java?

Any variable either a member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declared with static keyword in java and treated as constant. Here is an example of final variable in Java

public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error

Final variables are by default read-only.




3. What is the final method in Java?

The final keyword in Java can also be applied to methods. A Java method with the final keyword is called a final method and it can not be overridden in the subclass. You should make a method final in Java if you think it’s complete and its behavior should remain constant in sub-classes. 

In general, final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded at compile-time, See these Java Performance courses for more details. 

Here is an example of a final method in Java:

class PersonalLoan{
 public final String getName(){
     return "personal loan";
 }
}
class CheapPersonalLoan extends PersonalLoan{
    @Override
    public final String getName(){
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}



4. What is the final class in Java?

Java class with the final modifier is called the final class in Java. The final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer, and other wrapper classes. Here is an example of final class in java

final class PersonalLoan{

}

class CheapPersonalLoan extends PersonalLoan{  //compilation error: cannot inherit from final class
 
}




Benefits of final keyword in Java

Here are a few benefits or advantages of using the final keyword in Java:

1. Final keyword improves performance. Not just JVM can cache the final variables but also applications can cache frequently use final variables.

2. Final variables are safe to share in a multi-threading environment without additional synchronization overhead.

3. Final keyword allows JVM to an optimized method, variable or class.


Final and Immutable Class in Java

Final keyword helps to write an immutable class. Immutable classes are the one which can not be modified once it gets created and String is a primary example of an immutable and final class which I have discussed in detail on Why String is final or immutable in Java.

Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in Java.

Example of Final in Java

Java has several system classes in JDK which are final, some examples of final classes are String, Integer, Double, and other wrapper classes. You can also use a final keyword to make your code better whenever it is required. See the relevant section of the Java final tutorial for examples of the final variable, final method, and final class in Java.




Important points on the final modifier in Java

1. The final keyword can be applied to a member variable, local variable, method, or class in Java.

2. The final member variable must be initialized at the time of declaration or inside the constructor, failure to do so will result in a compilation error.

3. You can not reassign the value to a final variable in Java.

4. The local final variable must be initialized during declaration.

5. The only final variable is accessible inside an anonymous class in Java,, but in Java 8, there is something called effectively final variable, which is non-final local variables but accessible inside the anonymous class. 

The only condition is that they should not be reassigned a value once created. If you do so, the compiler will throw an error.  See Java SE 8 for Really Impatient for more details.

What is final in Java?


6. A final method can not be overridden in Java.

7. A final class can not be inheritable in Java.

8. Final is different than finally keyword which is used for Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in Object class and called before an object is garbage collected by JVM.

10. All variables declared inside the Java interface are implicitly final.

11. Final and abstract are two opposite keywords and a final class can not be abstract in Java.

12. Final methods are bonded during compile time also called static binding.

13. Final variables which are not initialized during declaration are called a blank final variable and must be initialized in all constructors either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method, or variable final in Java helps to improve performance because JVM gets an opportunity to make assumptions and optimization.

15. As per Java code convention, final variables are treated as constant and written in all Caps like

private final int COUNT=10;


16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:

private final List loans = new ArrayList();
loans.add(“home loan”);  //valid
loans.add("personal loan"); //valid
loans = new Vector();  //not valid


That’s all on final in Java. We have seen what is final variable, the final method is, and the final class in Java and what do those mean. In Summary, whenever possible start using final in java it would result in better and faster code.


Java Tutorial you may like:
How to debug Java program in Eclipse

Thanks for reading this article so far, if you like this tutorial then please share it with your friends and colleagues. If you have any questions then please drop a comment. 

22 comments :

michee said...

what's the difference between final and immutable?

Great blog!
Happy New Year!

Anand Vijayakumar said...

@ Michee - Immutable approximately means the same as a final. Something that cant be changed. But, in Java, the term immutable is usually used along with String objects when we say Java String objects are Immutable.

Anand
Inheriting Java

Santu said...

Can final variables cloned along with object ?

ravi said...

Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical example of Race condition

Read more: http://javarevisited.blogspot.com/2012/02/what-is-race-condition-in.html#ixzz1xRNIKEnV

POJO said...

Making a class final is double edged sword, Some Java programmer argue that final class severely limits client's ability to inherit and extend while Some Java programmer are in opinion that final class, which is Immutable are best way to design robust System.It's trade-off. James Gosling suggest that Making a class final in Java for security reason e.g. String can be justified.

Anonymous said...

What is blank final variable in Java ? is it mandatory to initialize blank final variable in Constructor ? What is my class have multiple constructor, do I need to initialized blank final variable in all constructor or is there any alternative of that ?

Shirin said...

A blank final, means that it's not initialized explicitly at it's declaration, can only be initialized in an initialization block or a constructor. A reference, declared final, doesn't make the object final.

Anonymous said...

Can you please suggest when to use final methods in Java, what are best practices around using final. I mean, I always get confused, should I make a class final or not, is there a rule book which we can follow? I hope my IDE suggest this but not so far.

Jon Schneider said...

> "Local final variable must be initializing during declaration."

This doesn't seem to be correct? For example, the following snippet compiles and runs okay under Java 1.7.0:

final int f; // Declare a final local variable
System.out.println(new java.util.Date()); // Do some other things
f = 5; // Initialize the final variable
System.out.println(f); // Use the final variable

If you then attempt to add a second assignment of the f variable, that *does* cause a compile-time error ("variable f might already have been assigned").

Anonymous said...

Can you please provide some examples of final methods from Java API? I am learning final keywords and want to know more about, how to use final with methods.

Unknown said...

Can you provide the solution of this Q??
Q:As we know that if at any point some exception occurs in the code then an instance of Exception class (or its subclass) is thrown from that point. So my question is the instantiation comes into picture at runtime while checked exception are checked at compile time , therefore no instantiation is there, so how compiler comes to know that it is a compile time exception.

Sudha said...

One Suggestion
You had cover everything about final here. One thing which as if i know is missing is about final instance variable,final static variable and final local variable (which you cover) missed is about the default values what we get for instance and static variable we will not get for final instance and final static variables , where we can initialize them in constructor and initialization block,final local variable will compile fine if we are not using it in code . Write something about this final keyword will get cover fully .

You can write to me at sudha.enigmatic@gmail.com

Unknown said...

"You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java"

I don't agree with this statement, a very simple example would be:
- a final class can still be mutable if its fields are non-final and are not-private or have setters available for them
- similarly a non-final class can still be immutable if all its fields are final or are either private with no setters provided for them

Anonymous said...

One more thing to note about final variables in Java is that, till Java 7, you can not use a non final local variable inside anonymous class, but from Java 8 you can. JDK 8 introduced a concept called effective final, a variable is considered effective final if it is not modified after initialization in local block. What this means is you can now use local variable without final keyword inside anonymous class or lambda expression, provided they must be effectively final. In short, you can save some keystroke while declaring local final variables indented to be used by anonymous class. Here is an example of using effective final variable in Java 8 :


public class EffectiveFinalJava8 {

public static void main(String[] args) {

String nonFinal = "I am non final local variable";
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Using non-final local variable inside anonymous class in Java");
System.out.println("Value of non-final variable is : " + nonFinal);

// compile time error - must be final or effective final
// nonFinal = "Can I change non-final variable inside anonymous class";
}
};
}

}

codingdog said...

For the last example, shouldn't it be "Loans.add(“home loan”);
Loans.add("personal loan");" ?

Anonymous said...

Final object references
The fields on any object accessed via a final reference are also guaranteed to be at least as up to date as when the constructor exits. This means that:

Values of final fields, including objects inside collections referred to by a final reference, can be safely read without synchronization.
Note that if you have a final reference to a collection, array, or some other mutable object, you must still synchronize all accesses to that object (or use a thread-safe collection such as a ConcurrentHashMap) if that collection is ever accessed by a thread other than the constructing thread.
Thus, immutable objects (ones where all fields are final and are either primitives or references to immutable objects) can be concurrently accessed without synchronization. It is also safe to read "effectively immutable" objects (ones whose fields aren't actually final, but in practice never change) via a final reference. However, from a program design perspective, you'd be wise to try and enforce immutability in this case (e.g. by wrapping a collection in a Collections.unmodifiableList()1 etc). That way, you'll spot bugs introduced when one of your colleagues naughtily attempts to modify a collection that you didn't intend to be modified!

Anonymous said...

Nice article.. very much useful! Thank you! btw....Last example, it should be corrected as follows
Loans.add("home loan"); //valid
Loans.add("personal loan"); //valid

javin paul said...

@Anonymous, good catch. That's right, the collection should be Loans there.

Unknown said...

private final List Loans = new ArrayList();
list.add(“home loan”); //valid
list.add("personal loan"); //valid
loans = new Vector(); //not valid
In the above code snippet the name of the variable should be list instead of Loans... as per my knowledge

javin paul said...

@Sehsh, you are right, that was typo, variable name is loans there not list. Corrected it now.

Unknown said...

what about final Object with some member functions. If you make an Object of a non-final class final then How will it behave what sort of member function will it be able to invoked and what will it restrain remember the class is non-final that is regular class

Suraj Tamang said...

The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).
{Taken from: https://www.ibm.com/developerworks/java/library/j-jtp1029/index.html }

Post a Comment