What is a Constant in Java?

A constant in Java is used to map an exact and unchanging value to a variable name.

Constants are used in programming to make code a bit more robust and human readable. Here's an example:

Imagine you are creating a program that needs to calculate areas and volumes of different shapes, it could look something like this, but this is an example of WHAT NOT TO DO:

public class AreasAndVolumes
{
  public double volumnOfSphere (double radius)
  {
    return (4/3) * Math.pow(3.14159 * radius, 3);
  }

  public double volumeOfCylinder (double radius, double height)
  {
    return Math.pow(radius * 3.14159, 2) * height;
  }

  public double areaOfCircle (double radius)
  {
    return Math.pow(radius * 3.14159, 2);
  }
}

So, this above code will get the job done, but there's something that can be improved. Can you guess how?

We should be using a constant! Look how many times we use the double value 3.14159, this value represents pi (π). We should create a constant that will assign the value of π to a variable name. Here's how we do it with some new code:

public class AreasAndVolumes
{
  // here we've declared a new variable called PI and assigned
  //  the value of 3.14159 to this new variable.
  private static final double PI = 3.14159;

  public double volumnOfSphere (double radius)
  {
    return (4/3) * Math.pow(PI * radius, 3);
  }

  public double volumeOfCylinder (double radius, double height)
  {
    return Math.pow(radius * PI, 2) * height;
  }

  public double areaOfCircle (double radius)
  {
    return Math.pow(radius * PI, 2);
  }
}

So now, we have a variable named PI declared in the instance variable declaration space. We've done this because we need to use this new constant value throughout our AreasAndVolumes class. This constant will function just like any other instance variable with one main exception… we've made the value final.

The final Keyword

Here is the magic behind a constant value. When you declare a variable to be final we are telling Java that we will NOT allow the variable's “pointer” to the value to be changed.

That last sentence is key to understanding constants, did you read it thoroughly? If not, re-read it.

What the final keyword means is that once the value has been assigned, it cannot be re-assigned. So if you tried to put in some code later that tries to do this:

PI = 3.14159265359

You would get a compilation error, and your IDE would tell you that a new value cannot be assigned because the variable has been declared final.

Does that make sense? A constant is a constant for a reason, it shouldn't ever change! Now, here's a quick note on conventions in Java. When you name a constant, you should use UPPER_CASE_LETTERS_WITH_UNDERSCORES_INDICATING_SPACES. Again, it's not mandatory to use upper case letters with underscores to indicate spaces, but it's a convention that programmers use and are familiar with in Java. So why fight it?

private vs public Constants

So what you saw in the examples so far, were just private constants. This means that no other Classes in your Java project would be able to use the constant value. Sometimes you want it that way because you like to keep your constants organized into the classes where they'll be used. This is a perfectly acceptable (and encouraged) way to handle your constants, but let's say that you have a constant that needs to be used in multiple Classes. You wouldn't want to declare two separate private constants in two Class files right? So I recommend you pick a Class that best fits the constant and declare it as public.

Important Note: You may find examples on the internet of people declaring ALL of their constants in ONE file and that file is declared as an interface. I DO NOT recommend this approach, as it is a dated approach to handling constants. Since those times, Java has implemented something called a static import which will negate the usefulness of storing constants in an interface. So let's see an example of a public constant being used with a static import shall we?

Images.java file:

import java.io.File;

public class Images
{
  public static final String THUMBNAILS_DIRECTORY = "C:\images\thumbnails";

  public void doSomethingWithThumbnails ()
  {
    File thumbnailFile = new File(THUMBNAILS_DIRECTORY);

    // do something with thumbnailFile.....
  }
}

AnotherClass.java

import java.io.File;
import static com.howtoprogramwithjava.test.Images.THUMBNAILS_DIRECTORY;

public class AnotherClass
{
  public void doSomethingElseWithThumbnails ()
  {
    File thumbnailFile = new File(THUMBNAILS_DIRECTORY);

    // do something else with thumbnailFile.....
  }
}

One thing to note here is that we've chosen to declare the THUMBNAILS_DIRECTORY in the Images Class, but we made the constant public… this allows us to reference that same value in another Class file, which is what you see in AnotherClass where we use THUMBNAILS_DIRECTORY when creating a File. This was possible because of the static import, like so:

import static com.howtoprogramwithjava.test.Images.THUMBNAILS_DIRECTORY;

We are importing the constant from the Images into AnotherClass file so that it can be used just like we declared it inside of AnotherClass. Neat stuff!

One other small thing to note here, is the use of the double backslashes when listing the actual thumbnails directory. You'll see that I declared the constant with this value: "C:\images\thumbnails"… this is a bit confusing, because why in the heck am I using two backslashes (\) between directories? Well, this is because in Java, the backslash () is a special character known as an escape character. It's used when you want to insert a particular character somewhere without having that character interfere with your code… (not a very good explanation, but here's a great example):

String aSentence = "Here's a great quote "Behind every great man, is a woman rolling her eyes - Jim Carrey".";

Notice how I wanted to put the quote (“) symbols inside of my String variable, but I wouldn't normally be able to do this, because the quote (“) symbol is used to denote the start and end of a String. Well, I get around this by using the backslash () escape character.

So, in summary, if you want to actually have Java output a backslash () character, you need to escape the escape character (yes I know, it sounds strange). This is done by using two backslashes (\). In short:

Input: \
Output:

Input: \\
Output: \

Make sense?

Good, great, grand!

Free Java Beginners Course

Start learning how to code today with our free beginners course. Learn more.