✍️ Declaring constants in Java (Part I)

In this article, I explain the ways we can declare constants in Java.

✍️ Declaring constants in Java (Part I)
Constants if declared nicely would never change.

Hi! My name is Narendra Vardi, and I write about my learnings, observations and trends in the Software world. Besides software, I also talk about photography, travel stories, books and movies. If that's something that interests you, consider subscribing.


There is a bit of easy code in this article. Don't feel intimidated! :D

One of the common indicators that shows you are an experienced Java developer is the effective use of constants.

Various programming languages provide a keyword called const to represent a constant. But Java doesn't use this keyword. In Java, there are special ways of creating a constant.

Before we learn about the way to declare constants, let me tell you when I use constants.

If the below two conditions are satisfied, I prefer using a constant variable.

  1. Once a variable is declared, its value shouldn't change and
  2. The value of variable remains same if you declare it once or n number of times.

Using final keyword

Take for example you are building a program to calculate the area of circle or perimeter of a circle, The number π is a well-known constant whose value shouldn't change.

So, we can declare π as a variable pi with the help of final keyword as

public class Main {
  // five digit precision
  final double pi = 3.14159;

  public static void main(String[] args) {
    Main main = new Main();
    System.out.println(main.pi);
  }
}

Here, final keyword indicates that the variable's value cannot be changed.

If we try to re-assign some other value to pi, it would lead to a compilation error.

public class Main {
  final double pi = 3.14159;

  public static void main(String[] args) {
    Main main = new Main();
    main.pi = 10.0; // compilation error.
    System.out.println(main.pi);
  }
}

But the problem with using final is, that pi variable will be created for each instance of Main class. But the value of pi is constant across all the instances of this class.

pi is a smaller variable and let's agree we are okay with creating n number of times. But what if you want to open and store a config file of 10kb size into a constant? It became an expensive operation isn't it?

This is where the next step comes, declaring the variable in such a way that the variable is created only once.

Using Static keyword

This is where we can make use of static keyword. Static keyword helps us to avoid creating duplicate copies of same constant. Thus making our application optimised for memory and compute.

public class Main {
  final static double pi = 3.14159;

  public static void main(String[] args) {
    System.out.println(pi);
  }
}

Since static memory is shared by all the instances of Main class, we are creating pi variable only once.

Naming convention

To help developers identify that a variable is a constant and shouldn't be modified, in Java, naming convention that is following for declaring constant variables is to use upper snake case.

Upper snake case is a variable naming convention where each word is in upper case, and separated by underscores. It is also known as MACRO_CASE or CONSTANT_CASE.

Finally our program looks like the following:

public class Main {
  final static double PI = 3.14159;

  public static void main(String[] args) {
    System.out.println(PI);
  }
}

Now, that's the basics of declaring constants.

Declaring int constant

public class Main {
  final static int TEN = 10;

  public static void main(String[] args) {
    System.out.println(TEN);
  }
}

Declaring Integer constant

public class Main {
  final static Integer TEN = 10;

  public static void main(String[] args) {
    System.out.println(TEN);
  }
}

Adding access specifier depending on your use case

public class Circle {
  private final static double PI = 3.14159;

  // radius variable declaration
  // area and perimeter functions
}

In the Circle class, we are using private for PI since it need not be exposed to outside world as all computations which use it like area and perimeter functions are inside the class only.

public class ApplicationConstants {
  public final static double PI = 3.14159;
  // other application constants.
}

In the ApplicationConstants class, we are using public for PI since it is declared in a constants class which only has constants and it will be re-used by all the classes within the application.

In this article, I have not talked on how to declare collection and complex object constants. Will talk about them in the later articles.

Hope you got an idea on how to use static and final keywords to declare constants. In case of any queries, please feel free to comment below or shoot an email.


Share this article

Copy and share this article: narendravardi.com/declaring-constant-variables-in-java/


Recommendations

If you liked this article, you might also enjoy reading the following.


❤️ Enjoyed this article?

Forward to a friend and tell them where they can subscribe (hint: it's here).

Anything else? Comment below to say hello, or drop an email!