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 can not 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.
- Java Interview Questions-Core Faq
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What does it mean to be static in Java?