What is a Constant?

by Trevor Page on December 1, 2012

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!

As always, if something doesn’t make sense to you, please post a comment below and ask a question. I’ll address the question ASAP :) And if you’re really keen on learning Java, I invite you to check out my new Java Video Tutorial series, you’ll receive access to a new video tutorial every week and an actual test that you’ll have to take and pass before proceeding to the next test. This way I ensure that you are understanding all of the important concepts that are needed to be a great programmer! So if you like this tutorial, you’ll absolutely love http://javavideotutorials.net.

{ 10 comments… read them below or add one }

Ali Nawkhas Murad December 2, 2012 at 3:54 am

Hi Trevor
I thinks there is some wrong in math expression, please make sure and the correct is look like the following which is correct:

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

and also for other subsequent topic in the same page.
Ali Nawkhas Murad

Reply

Trevor Page December 2, 2012 at 9:30 am

Thanks Ali,

I threw together those calculations too quickly, thanks for the correction :) Clearly it’s been far too long since I’ve attended a real math class!

Reply

Java lover December 2, 2012 at 12:59 pm

Its a good article, even as a developer this is very basic knowledge. we should use constant because it make code easy to understand and maintain, when Java compile your code, it actually replace your constant variable to real value.

Reply

Eric Jablow December 2, 2012 at 4:21 pm

The java.lang.Math class already has a constant PI. You should not use your own.

Furthermore, you should not try to use a decimal for π, because the double closest to π may not be directly representable as a fixed decimal expression, or the obvious decimal expression might not be useful. This is why many programming systems in the past have defined π by 4.0 * tan^{-1} 1.

There is one peculiar reason why constants are unreliable. Suppose you define a constant in class A, and use it in class B:

// class A
public static final int BUF_SIZE = 1024;

// class B
public char[] buffer = new char[A.BUF_SIZE];

When javac compiles these classes, Java inlines A.BUF_SIZE, and class B has no reference to class A. Now, suppose you decide to change BUF_SIZE from 1024 to 2048. You recompile A.java, but not B.java. B still uses 1024.

Reply

Trevor Page December 2, 2012 at 4:51 pm

I’m not using Math.PI as I’m trying to explain constants by declaring my own and using static import.

Reply

newbie May 16, 2013 at 5:25 am

static double PI
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

Reply

Muhammad Anis December 3, 2012 at 8:25 am

awesome…….the method of teaching is very Good .i m enjoying

Reply

sawan August 3, 2013 at 2:19 pm

need more suitable example

Reply

Kaushik July 29, 2014 at 8:40 am

Why do we have to use static keyword ? The word ‘final’ already makes it a constant , right ?

Reply

Trevor Page July 29, 2014 at 10:36 am

The static keyword allows us to refer to this value from anywhere in our application without having to instantiate the object it belongs to.

So if you’ve created the constant: public final int SOME_CONSTANT = 4; and this variable was declared inside of a class called MyObject, you would have to instantiate MyObject before you could access the value of the constant (since you didn’t declare it as static).

Your (bad) code would look like this:

MyObject anObject = new MyObject();
System.out.println("Some constant is: " + anObject.SOME_CONSTANT);

Now let’s assume you’ve declared the constant with the static keyword… now here’s how we would access the value:

System.out.println("Some constant is: " + MyObject.SOME_CONSTANT);

Reply

Leave a Comment

Powered by sweet Captcha

Previous post:

Next post: