How To Declare a Constant in Java
This is one of the articles from our Java Tutorial for Beginners.
In mathematics, there is a concept called a constant, which is a fixed value that cannot be changed. One example of a constant is pi, because it always has the same value, which is 3.14159… This concept of constants is relevant to us, because we often need to declare constants when we write programs in Java.
How To Declare a Constant in Java
- To turn an ordinary variable into a constant, you have to use the keyword "final."
- As a rule, we write constants in capital letters to differentiate them from ordinary variables.
- If you try to change the constant in the program, javac (the Java Compiler) sends an error message. This happens because you can only assign a value to a constant once.
Let's see how this works in practice.
Task:
Calculate the perimeter of a circle with the radius of the following values:
- R = 10 cm.
- R = 25 cm.
Solution:
You can find the perimeter of circle with the formula: P= 2πR
P = the perimeter of a circle
π = Pi (3.141592…)
R = the radius of a circle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Test { public static void main(String[] args) { final double Pi = 3.1415926536; /* Since the constant Pi is a floating point variable, we have to make variables length1 and length2 either float or double. /* double lengthl = 2*Pi*10; double length2 = 2*Pi*25; System.out.println ("The perimeter of a circle with a radius of 10 cm. is " + lengthl + ", and the perimeter of a circle with a radius of 25 cm. is " + length2); } } |
If you run this code on your computer, you will see the following message in the console:
The perimeter of a circle with a radius of 10 cm. is 62.831853072 and the perimeter of a circle with a radius of 25 cm. is 157.07963268
Commentary:
1 |
final double Pi = 3.1415926536; |
In this line of code, we turned the variable Pi into a constant. How did we do this? By adding the keyword "final" to the beginning of the code. If you try to change the value of this constant, javac (the Java Compiler) will give you an error message, because you can only set the value of a constant once.
You can find more articles in our Java Tutorial for Beginners.