Declaring Constants in Java

Constant in programming is a variable that never changes.

Today I’ll tell you about declaring constants in Java.

Java doesn’t have a special keyword to define a constant.

const is reserved keyword (you can’t use it as a name of a variable for example), but it’s unused.

So to declare a constant in Java you have to add static final modifiers to a class field.

Example:

You should follow Java constant naming convention – all constant variables should be in upper case, words should be separated by the underscore.

Declaring Constants Class In Java

Sometimes programmers are defining constants in a separate class in Java

First of all, it’s a really bad idea to create a single class for all constants in your project. 

Constants should be related to each other.

For example, I have a UserController, that contains endpoints to work with users.

Each endpoint has a binding to specific URL.

So I can create a class with Java string constants that contains user controller bindings.

Example:

The best practice of defining constants class in Java is:

  • Add a final attribute to class to restrict inheritance.
  • Add a private no-args constructor to forbid new instance creation.

Defining Constants in Java Interface

All fields in the interface are constants.

By default, each variable in the interface is  public static final and you can’t change it.

I’ll change our UserBinding to an interface.

Example:

But defining constants in the interface is a bad practice.

It’s called Constant Interface Antipattern.

Joshua Bloch in his book “Effective Java” said:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants . These interfaces should be regarded as anomalies and should not be emulated.

So my recommendation is to use class for constants.

Tips & Tricks

If you’re using Intellij IDEA to write a code I have 3 live templates for you:

psf + TAB generates  public static final.

psfs  + TAB generates  public static final String.

psfi  + TAB generates  public static final int.

Learn your favorite IDE shortcuts and live templates to increase your productivity.

1 Star2 Stars3 Stars4 Stars5 Stars
Loading...
Scroll Up