What are final variables in Java?
The keyword final is a reserved keyword in Java to restrict the user and it can be applied to member variables, methods, class and local variables. The final keyword indicates that a variable may only be initialized once. That means, the compiler makes sure that you can do it only once.
The java final keyword can be used in various context:
- final variable - A variable declared as final prevents the content of that variable being modified
- final method - A method declared as final prevents the user from overriding that method
- final class - A class declared as final cannot be extended thus prevents inheritance
The final keyword as applied to a variable inside a class means that variable can only be initialized once and its reference cannot be altered once it assigned. For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.