Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Constant Declaration: Syntax and Best Practices

Learn the correct syntax for Java constant declaration, the difference between compile-time and runtime constants, and when to choose an enum over static final fields.

~5 min readJava
#Java#constants#final#enum
Java constant declaration showing final static field and enum comparison in a clean diagram

Declaring a constant in Java is straightforward, but the right form depends on the value and how it will be used. The most common Java constant declaration is public static final, but that is not always the best choice. This article covers the syntax, the behavior of compile-time constants, and the tradeoffs between final fields and enum constants.

The Basic Syntax for a Constant

A constant in Java is typically a variable whose value cannot change after initialization. The final keyword enforces that rule, but final alone is not enough for a class-level constant. Consider this declaration:

java
public class Config { public final int MAX_RETRIES = 5; }

This is a final instance field. Every Config object gets its own copy of MAX_RETRIES, and the field initializer runs when objects are constructed. If the field were blank final (no initializer), a constructor could assign a different value for each instance. In either case, the value is not shared at class level, so this is not a conventional class-level constant. For a shared class-level constant, use static final.

Compile-Time Constants vs Runtime Constants

A compile-time constant is a final variable of primitive type or String that is initialized with a constant expression, such as a literal or an expression built from literals and other constants. For example:

java
public static final int TIMEOUT = 30;

Any code that references TIMEOUT is compiled with the literal 30 embedded. If a library changes the value of such a constant, classes that reference it must be recompiled; otherwise they may keep using the old value. This matters for binary compatibility when a library exposes such a constant.

Runtime constants, as used here, are final fields initialized with a non-constant expression, such as a method call. They are not inlined, so changing the value does not require recompiling consumers. Use this form when the value is not known at compile time.

Using static final for Class-Level Constants

The standard way to declare a class-level constant is public static final. The static modifier makes the field belong to the class rather than to an instance, and final guarantees that the primitive value or reference cannot be reassigned. For example:

java
public class DatabaseConfig { public static final String URL = "jdbc:mysql://localhost:3306/app"; public static final int PORT = 3306; }

Access is straightforward: DatabaseConfig.URL. By convention, constant names use uppercase letters and underscores. This pattern works well for simple values that are not logically grouped. However, it has limitations. There is no type safety beyond the declared type, and related constants are not grouped in a namespace. If you have a set of related constants, an enum is often a better fit.

When to Use an Enum Instead of Multiple Constants

When you need a fixed set of related values, an enum provides type safety and a natural grouping. Compare these two approaches:

java
// Multiple static final constants public static final int STATUS_ACTIVE = 1; public static final int STATUS_INACTIVE = 2; public static final int STATUS_PENDING = 3;
java
// Enum public enum Status { ACTIVE, INACTIVE, PENDING }

With the int constants, any method that accepts a status can be passed any integer, leading to invalid values at runtime. The enum restricts the set of valid values at compile time. It also allows you to attach behavior and data to each constant, which is impossible with plain final fields. For example:

java
public enum Status { ACTIVE("The record is live"), INACTIVE("The record is hidden"), PENDING("The record awaits review"); private final String description; Status(String description) { this.description = description; } public String getDescription() { return description; } }

Use an enum when the constants form a closed set and you want compile-time checking. Use static final for individual values that do not belong to such a set, such as a timeout or a port number.

Constants in Interfaces and Why That's Controversial

The Constant Interface Antipattern places constants in an interface and then implements that interface to access them without qualification:

java
public interface Constants { int MAX_SIZE = 100; String DEFAULT_NAME = "unknown"; } public class Service implements Constants { // can refer to MAX_SIZE directly }

This works because fields in an interface are implicitly public static final. However, it leaks the constants into the public API of every implementing class, and it can lead to namespace pollution. This pattern is widely considered an antipattern. A better approach is to put constants in a final class with a private constructor to prevent instantiation, or to use an enum if the constants are related.

Common Mistakes in Constant Declaration

One frequent mistake is forgetting static and declaring public final int MAX = 10;. This creates an instance field, so every object has its own copy. If the value is meant to be shared, this wastes memory. If the field is declared without an initializer and constructors assign different values, it can also lead to inconsistent values across instances.

Another mistake is using final on a reference to a mutable object. For example:

java
public static final List<String> NAMES = new ArrayList<>();

The reference NAMES is final, but the list itself is mutable. Callers can add or remove elements, so the constant is not truly immutable. For collections, use List.of() (Java 9+) or Collections.unmodifiableList() to make the collection unmodifiable.

Impact on Performance and Memory

Compile-time constants are inlined by the compiler, which can reduce runtime lookups. However, this inlining also means that changing the constant requires recompiling dependent code. For a library, this can cause stale values if consumers are not rebuilt. Runtime constants avoid that issue but require a field read at runtime, which is negligible in most applications.

Memory usage is another consideration. A static final primitive field is stored once per class. An enum constant is an instance of the enum class, so each constant has a small object overhead. For a handful of constants, the difference is irrelevant. For a large set of numeric constants, static final ints are more memory-efficient. The choice should be driven by type safety and maintainability, not by micro-optimization.

A final note on static final fields that reference mutable objects: if you expose the object directly, callers can mutate it, breaking the constant contract. Always return an unmodifiable view or copy in a getter if the constant is a collection or an array. For arrays, clone the array or use Arrays.copyOf when exposing it. This protects the constant's integrity and prevents unexpected state changes.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.