What is ‘final’ variable in Java? Explained with example.

 In Java, a final variable is a variable whose value cannot be changed after it is initialized. Final variables are declared using the “final” keyword and once a value is assigned to a final variable, it cannot be reassigned.

There are several benefits to using final variables. For example, final variables can be used to ensure that the value of a variable does not change accidentally. They can also be used to create constants, which are variables that have a fixed value that does not change throughout the lifetime of the program.

Here is an example of a final variable being used as a constant:


final double PI = 3.14;

In this example, the variable “PI” is declared as a final variable and assigned the value 3.14. Since it is final, its value cannot be changed.

Final variables can also be used to create “final” or “immutable” objects. An object is considered immutable if its state cannot be modified once it is created. This can be useful in situations where you want to ensure that an object’s state cannot be modified by mistake.

Here is an example of a final variable being used to create an immutable object:


final List<String> myList = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

In this example, the variable “myList” is declared as a final variable and assigned an unmodifiable list of strings. Since it is final, its reference cannot be reassigned to a different list, but the elements of the list can still be accessed.

It is also worth noting that final variables can be used to create final methods and final classes as well. A final method cannot be overridden and a final class cannot be extended.

In conclusion, final variables in Java are variables whose value cannot be changed after they are initialized. They can be used to create constants and immutable objects. They can also be used to create final methods and final classes. By using final variables, developers can ensure that the value of a variable does not change accidentally and create more secure and predictable code.