How To Declare a Constant in Java

FacebooktwittertumblrFacebooktwittertumblr

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
  1. To turn an ordinary variable into a constant, you have to use the keyword "final."
  2. As a rule, we write constants in capital letters to differentiate them from ordinary variables.
  3. 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:

  1. R = 10 cm.
  2. 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

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:

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. 

 

FacebooktwittertumblrFacebooktwittertumblr

FacebooktwittertumblrFacebooktwittertumblr
Самоучители--узнать детальнее--