How to Use a Constant in Java

Using a Constant in Java Can Improve Your Application's Performance

Girl working with the notebook in green office
Photography by Bobi/Moment/Getty Images

A constant is a variable whose value cannot change once it has been assigned. The Java language doesn't have built-in support for constants, but the variable modifiers static and final can be used to effectively create one.

How the Static and Final Modifiers Work to Create a Constant

Here's what static and final do:

  • The static modifier allows a variable to be used without first creating an instance of the class; a static class member is associated with the class itself, rather than an object, and all class instances share the same copy of the variable.This means that another application or main() can easily use it. For example, class myClass contains a static variable days_in_week:

    public class myClass {
        static int days_in_week = 7;

    Because this variable is static, it can be used elsewhere without explicitly creating a myClass object, like so:

    public class myOtherClass {    
        static void main(String[] args) {

  • The final modifier means that the variable's value cannot change. Once the value is assigned, it cannot be reassigned. Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) can be made immutable  (or unchangeable) using the final modifier.

Together, these modifiers create a constant variable. Let's see how this looks:

static final int DAYS_IN_WEEK = 7;

Note that we declared DAYS_IN_WEEK in all caps, once we added the final modifier. It's a long-standing practice among Java programmers to define constant variables in all caps, as well as to separate words with underscores. The Java language does not require this formatting,  but it makes it easier for anyone reading the code to immediately identify a constant. 

When Using a Constant is Good Practice

Constants can make your program more easily read and understood by others. In addition, a constant is cached by the JVM as well as your application, so its use can improve performance.


Potential Problems with Constant Variables

The way the final keyword works in Java is that the variable's pointer to the value cannot change — let's repeat that: it's the pointer that cannot change the location to which it is pointing. There is no guarantee that the object being referenced will stay the same  —  only that the variable will always hold a reference to the same object.

If the referenced object is mutable, i.e. has fields that can be changed, then the constant variable may contain a value other than that originally assigned. 

mla apa chicago
Your Citation
Leahy, Paul. "How to Use a Constant in Java." ThoughtCo, Sep. 30, 2017, Leahy, Paul. (2017, September 30). How to Use a Constant in Java. Retrieved from Leahy, Paul. "How to Use a Constant in Java." ThoughtCo. (accessed March 20, 2018).