Please help me understand the difference between constant variables and final
variables in Java. I am a bit confused with it.
Constant is the concept, the property of the variable. final is the java keyword to declare a constant variable. As other people pointed out, from a semantic/linguistic point of view the expression constant variable is an oxymoron and, as such, we could argue about its correctness.
The only difference between the final and const keyword is that final is a runtime-constant, which in turn means that its value can be assigned at runtime instead of the compile-time that we had for the const keyword.
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes. Once any entity (variable, method or class) is declared final , it can be assigned only once. That is, the final variable cannot be reinitialized with another value.
Constant is the concept, the property of the variable.
final
is the java keyword to declare a constant variable.
As other people pointed out, from a semantic/linguistic point of view the expression constant variable is an oxymoron and, as such, we could argue about its correctness.
Quoting the specification, anyway, we can read
A variable of primitive type [...], that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.
I suppose, hence, that we can accept (and consider correct) this binomial for our purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With