This question already has an answer here:
- Difference between Static and final? 10 answers
Please help me understand the difference between constant variables and final
variables in Java. I am a bit confused with it.
This question already has an answer here:
Please help me understand the difference between constant variables and final
variables in Java. I am a bit confused with it.
Constant
is not a keyword in Java.It is a concept to make any variable constant. For this we use
final
keyword in Java so that after initializing the variable with final keyword , no one can reassign the value of that variable.There are several values in the real world which will never change. A square will always have four sides, PI to three decimal places will always be 3.142, and a day will always have 24 hours. These values remain constant. When writing a program it makes sense to represent them in the same way - as values that will not be modified once they have been assigned to a variable. These variables are known as constants.
Declaring a Variable as a Constant
In declaring variables I showed that it’s easy to assign a value to a int variable:
We know this value is never going to change in the real world so we make sure it doesn’t in the program. This is done by adding the keyword modifier
final
:In addition to the
final
keyword you should have noticed that the case of the variable name has changed to be uppercase as per the standard Java naming convention. This makes it far easier to spot which variables are constants in your code.If we now try and change the value of
HOURS_IN_A_DAY
:we will get the following error from the compiler:
The same goes for any of the other primitive data type variables. To make them into constants just add the
final
keyword to their declaration.Where to Declare Constants
As with normal variables you want to limit the scope of constants to where they are used. If the value of the constant is only needed in a method then declare it there:
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
I suppose, hence, that we can accept (and consider correct) this binomial for our purpose.