What is the difference between const and final in Java?
In Java, the const keyword does not exist, so it cannot be compared. However, Java has a final keyword for variable, method, and class modification. The purpose of final is to make the modified variables, methods, or classes immutable, meaning their values cannot be changed or inherited or overridden.
Below are the specific uses and characteristics of the final keyword.
- final modifies variables.
- A variable modified by “final” is called a constant, and its value cannot be altered.
- Constants must be initialized when declared, and can only be initialized once.
- Constants are typically named using uppercase letters, with words separated by underscores.
- Constants can be directly used in a class without the need to instantiate an object.
- method marked as “final”
- Methods modified with the keyword “final” cannot be overwritten by subclasses.
- The final method can be inherited and called by subclasses, but cannot be modified.
- Final class:
- Classes that are modified by the “final” keyword cannot be inherited.
- All methods in a final class are automatically final.
In conclusion, the final keyword is used to create immutable constants, prevent methods from being overridden, and prevent classes from being inherited. However, the const keyword does not exist in Java.