We looked at variables in depth and understood how we can work with them in our programs. Many times in our programs, we come across situations where we need to assign a name to a constant value. Unlike variables, we need a guarantee that these values should not change during the execution of the program. Some examples of such values can be the constant pi. We want pi to always have a value of 3.14159. Other examples can be that of speed of light or number of days in a week.

Java provides a way to declare such constant values. The syntax to declare a constant value is this:

final type constantname = value;

The declaration starts with the keyword final, then you specify the data type. After that you specify the name that you want to give to your constant value. In the end you assign the value you want your constant to have and end the declaration with a semicolon.

It is like variable declaration just that the declaration needs to start with the keyword final and the value needs to be assigned. Like variables, constantname is an identifier so all identifier naming rules apply to constantname.

Here are a few examples:

final double PI = 3.14159;
final long SPEED_OF_LIGHT = 299792458;
final int DAYS_IN_A_WEEK = 7;

In the first example, we declare PI as a constant of type double and assign a value of 3.14159 to it. Similarly, in the next 2 examples we declare SPEED_OF_LIGHT & DAYS_IN_A_WEEK as constants of type long and int respectively and assign them appropriate values.

Generally, Java developers name the constants in capital letters. This makes it easier to identify them in the code. Remember that this is a convention or a best practice. The compiler doesn’t mandate this. The name of your constant just needs to follow all the identifier naming rules and the compiler will be happy.

Time to look at a BlueJ program to see constants in action:

public class ConstantsDemo
    public void computeCircleArea() {
        //PI is declared as a constant using the final keyword
        final double PI = 3.14159;
        double radius = 12.5;
        // PI = 3.1415926535;
        double circleArea = PI * radius * radius;
        System.out.println("Area of circle with Radius " + radius + " is " + circleArea);

We have ConstantsDemo class here. computeCircleArea method of this class, computes the area of a circle. We have declared PI as a constant of double data type using the keyword final. We have assigned a value of 3.14159 to our constant PI. Later, we use PI to calculate the area of the circle. I will execute the program to show you that it is working perfectly.

Now let me try to change the value of PI by uncommenting this line // PI = 3.1415926535; in computeCircleArea method above.

This is flagged as an error. The compiler is not allowing me to change the value of PI as I have declared PI as a constant using the final keyword.

This wraps up our discussion of Constants for now. We will look at the final keyword again when we discuss Classes.