Final variable in java

(Last Updated On: March 7, 2019)

Learn about final variable in java with example that is how to use final variable in a class field, methods parameter and in an interface in java.

We use final keyword before variables in java programs, so, we cannot modify the value once the final variable is initialized.

Final variables can be used in multiple situations, for example, you may want a class field to be final. Within a method parameter, so, we cannot modify it accidentally inside the method and used in an interface.

Final prevents a variable and method parameter to be modified

 

Examples of final variables in Java

Let’s see examples of using final variable for class field, as a method parameter and how we use in an interface in java programs.

 

Perquisite: class in java.

final class field

If we make a class filed final, then it cannot be modified and act as a constant. In this code, print() method is trying to modify the value of final field “a” resulting a compiler error that “final field X:a cannot be assigned”

 

 

Prerequisite: methods in java.

final variable in method parameter

If a parameter of a method is final then it cannot be modified inside the method. If we try then compiler complain as final local variable cannot be assigned. In below program, method m is trying to change the value of final variable y resulting an error.

 

Prerequisite: interface in java.

final variable in an interface

In an interface, all variables are by default final and they cannot be changed from outside of interface. Typically, we keep collections of constants in an interface in java application.