1. Technology

Using Constants

By

Portrait of intellectual man typing on laptop
Klaus Vedfelt/Taxi/Getty Images

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:

 int numberOfHoursInADay = 24;
 

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:

 final int NUMBER_OF_HOURS_IN_A_DAY = 24;

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 NUMBER_OF_HOURS_IN_A_DAY:

final int NUMBER_OF_HOURS_IN_A_DAY = 24;
NUMBER_OF_HOURS_IN_A_DAY = 36;

we will get the following error from the compiler:

cannot assign a value to final variable NUMBER_OF_HOURS_IN_A_DAY

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:


    public static int calculateHoursInDays(int days)
    {
        final int NUMBER_OF_HOURS_IN_A_DAY = 24;
        return days * NUMBER_OF_HOURS_IN_A_DAY;
    }

If it’s used by more than one method then declare it at the top of the class definition:


public class AllAboutHours{
   private static final int NUMBER_OF_HOURS_IN_A_DAY = 24;

   public int calculateHoursInDays(int days)
  {
     return days * NUMBER_OF_HOURS_IN_A_DAY;
   }

    public int calculateHoursInWeeks(int weeks)
  {
      final int NUMBER_OF_DAYS_IN_A_WEEK = 7;
      return weeks * NUMBER_OF_DAYS_IN_A_WEEK * NUMBER_OF_HOURS_IN_A_DAY;
   }
}

Notice how I’ve also added the keyword modifiers private and static to the variable declaration of NUMBER_OF_HOURS_IN_A_DAY. This means that the constant can only be used by its class (hence the private scope) but you could just as easily make it a public constant if you want other classes to have access to it. The static keyword is to allow the value of the constant to be shared amongst all instances of an object. As it's the same value for every object created it only needs to have one instance - see Static Fields for more information.

Using the Final Keyword with Objects

It’s very important to realize that when it comes to objects, Java does not support constants as you might expect. If you assign a variable to an object using the final keyword it means the variable will only ever hold the reference to that object. It cannot be changed to reference another object. However, it does not mean that the contents of the object cannot change. See Using the Final Keyword with Objects for more information.

A Brief Note on the Const Keyword

You may have noticed in the reserved words list that there is a keyword called const. This is not used with constants, in fact it’s not used at all in the Java language.

©2014 About.com. All rights reserved.