Final Keyword in Java

In this tutorial, we will learn about Final Keyword in Java.

In java Final keyword is used in different ways. Final is not an access-modifier. Final keyword can be applied to a variable, a method and a class.

Final keyword and its usages:

Final Keyword applied toUsage
a variableCreates a constant variable.
a methodTo prevent method overriding.
a classTo prevent inheritance.

Let’s learn about Final keyword in detail with an example.

Final variable:

If a variable is prefixed with final keyword, then the variable becomes a constant whose value cannot be changed. Hence when a constant needs to be created, prefix final keyword with the variable.

Generally final variables are represented in uppercase with underscore between the words.


//a final variable

final int count = 5;

Let’s see final variable with an example.

Let’s see the output.


Blank Final Variables:

Blank final variable is a variable that is not initialized at the time of declaration. We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error.

Let’s see with an example.

Check the output:

Static Final Variable:

//a static final variable

static final float price = 100.5;

//a blank static final variable

static final float price;

Final Method:

A method declared with final keyword is called as Final Method. A final method cannot be overridden.

Let’s see this with an example.

The above program throws compile time error as the method in super class is final and can’t be overridden.

Final Class:

A class declared with final keyword is known as Final class. A final class cannot be inherited/extended. Use final keyword with class to make the class immutable.

In java String class and all wrapper classes are immutable.

Let’s see with an example.

Other Tutorials:

Related posts

Leave a Comment