Constants
suggest changeJava has no const keyword. (const is reserved, but using it is a compile error.) A constant is a field declared static final: static so there is one copy per class, final so it can't be reassigned.
This article covers:
- declaring and naming constants
- compile-time constants vs. values computed at runtime, and why the difference matters
- the inlining trap: changing a constant without recompiling the classes that use it
finalmakes the reference constant, not the object- where to put constants: holder classes, enums, and why constant interfaces are a bad idea
- constants in
switch, local constants and effectively final variables - useful constants in the JDK
- lazy constants with
StableValue
All examples are single files you run with java Example.java. Output is from JDK 25.
Related articles: final, Constant Expressions, Initializing static final fields using a static initializer and Immutable Objects.
Declaring constants
public class Basics {
static final int MAX_RETRIES = 3;
static final double TAX_RATE = 0.23;
static final String APP_NAME = "Inventory";
static final long ONE_GB = 1L << 30;
static final int SECONDS_PER_DAY = 24 * 60 * 60;
public static void main(String[] args) {
System.out.println(APP_NAME + " retries=" + MAX_RETRIES);
System.out.println("tax on 100: " + 100 * TAX_RATE);
System.out.println("1 GB = " + ONE_GB + " bytes");
System.out.println("a day has " + SECONDS_PER_DAY + " seconds");
}
}
Inventory retries=3
tax on 100: 23.0
1 GB = 1073741824 bytes
a day has 86400 seconds
Constant names are UPPER_SNAKE_CASE by convention. Writing 24 * 60 * 60 costs nothing at runtime: the compiler computes 86400 and stores that, and the expression documents where the number comes from.
If you try to assign to a constant, it won't compile:
public class Reassign {
static final int MAX_RETRIES = 3;
public static void main(String[] args) {
MAX_RETRIES = 5;
}
}
Reassign.java:5: error: cannot assign a value to static final variable MAX_RETRIES
MAX_RETRIES = 5;
^
1 error
The usual modifier order is public static final (or private static final). Make a constant private unless other classes really need it. A public constant becomes part of your API, and the next section shows why that is a bigger commitment than it looks.
Compile-time constants vs. runtime values
Java treats two kinds of static final fields differently.
A constant variable (the JLS term, often called a compile-time constant) is a final field of a primitive type or String whose initializer is a constant expression: literals, operators, and other constant variables. Everything else is just a final field whose value is computed when the class is initialized:
| Declaration | Compile-time constant? |
|---|---|
static final int MAX = 10; |
yes |
static final String NAME = "app" + "-" + MAX; |
yes |
static final long MS = 5 * 1000L; |
yes |
static final Integer MAX = 10; |
no: Integer is not a primitive or String |
static final int MAX = Integer.valueOf(10); |
no: method call |
static final int MAX; assigned in a static {} block |
no: the initializer isn't part of the declaration |
static final Duration TTL = Duration.ofSeconds(30); |
no: not a primitive or String |
The difference shows up in three places: inlining, class initialization, and switch labels.
The inlining trap
The compiler copies the value of a compile-time constant into every class that uses it. The using class doesn't reference the field at all.
Here are two files:
public class Config {
public static final int MAX_USERS = 10; // compile-time constant
public static final Integer MAX_ADMINS = 10; // not a constant: boxed type
public static final int MAX_GROUPS = Integer.valueOf(10); // not a constant: method call
}
public class App {
public static void main(String[] args) {
System.out.println("users: " + Config.MAX_USERS);
System.out.println("admins: " + Config.MAX_ADMINS);
System.out.println("groups: " + Config.MAX_GROUPS);
}
}
Compile both and run:
$ javac -d out Config.java App.java
$ java -cp out App
users: 10
admins: 10
groups: 10
Now change all three values in Config.java to 20 and recompile only Config.java, as an incremental build might, or as happens when Config lives in a library jar you upgrade:
$ javac -d out Config.java
$ java -cp out App
users: 10
admins: 20
groups: 20
MAX_USERS still prints 10. javap shows why:
$ javap -c -cp out App
public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #15 // String users: 10
5: invokevirtual #17 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
11: getstatic #23 // Field Config.MAX_ADMINS:Ljava/lang/Integer;
...
25: getstatic #31 // Field Config.MAX_GROUPS:I
The compiler folded "users: " + 10 into the single string "users: 10" inside App.class. The other two fields are read with getstatic at runtime, so they pick up the new values.
In Config.class the constant is stored as a ConstantValue attribute (javap -v -cp out Config):
public static final int MAX_USERS;
descriptor: I
flags: (0x0019) ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: int 20
What to do about it:
- Make a value a
publiccompile-time constant only if it truly never changes:SECONDS_PER_DAY, a protocol's magic number, a maximum fixed by a specification. - For values that might change between versions (limits, default timeouts, version strings), expose them through a method or a field that isn't a compile-time constant, for example
public static int maxUsers() { return MAX_USERS; }. - When you change a constant, do a clean build so that every class using it is recompiled.
Inlining is also why if (DEBUG) { ... } with static final boolean DEBUG = false; costs nothing: the compiler drops the block completely. This is Java's equivalent of conditional compilation.
Constants and class initialization
Reading a compile-time constant doesn't initialize the class that declares it, because the value is already in the caller's bytecode. Reading any other static field does:
public class InitOrder {
static class Limits {
static final int MAX = 100; // compile-time constant
static final long STARTED = System.currentTimeMillis(); // computed at class init
static {
System.out.println("Limits initialized");
}
}
public static void main(String[] args) {
System.out.println("MAX = " + Limits.MAX);
System.out.println("about to read STARTED");
System.out.println("STARTED > 0: " + (Limits.STARTED > 0));
}
}
MAX = 100
about to read STARTED
Limits initialized
STARTED > 0: true
The static block only runs when STARTED is read. Usually this doesn't matter. It can surprise you if a static initializer has side effects, such as registering something or loading a native library, and you expected reading a constant to trigger it.
Computed constants
Many constants are objects or depend on the environment. They are still static final and computed once when the class is initialized:
import java.nio.file.Path;
import java.time.Duration;
import java.util.regex.Pattern;
public class Computed {
static final Pattern EMAIL = Pattern.compile("[a-z0-9._]+@[a-z0-9.-]+[.][a-z]+");
static final Duration SESSION_TTL = Duration.ofMinutes(30);
static final Path DATA_DIR = Path.of(System.getProperty("java.io.tmpdir"), "myapp");
static final int WORKERS = Runtime.getRuntime().availableProcessors() * 2;
static final boolean DEBUG = Boolean.parseBoolean(System.getenv().getOrDefault("APP_DEBUG", "false"));
public static void main(String[] args) {
System.out.println(EMAIL.matcher("ada@example.com").matches());
System.out.println(EMAIL.matcher("not an email").matches());
System.out.println("session ttl: " + SESSION_TTL.toSeconds() + "s");
System.out.println("data dir ends with myapp: " + DATA_DIR.endsWith("myapp"));
System.out.println("workers > 0: " + (WORKERS > 0));
System.out.println("debug: " + DEBUG);
}
}
$ java Computed.java
true
false
session ttl: 1800s
data dir ends with myapp: true
workers > 0: true
debug: false
$ APP_DEBUG=true java Computed.java
...
debug: true
Storing a compiled Pattern in a constant is a common way to avoid recompiling a regex on every call. Pattern and Duration are immutable and thread-safe, so sharing them is safe.
When the value takes several statements to build, use a static initializer or a private static method: static final Map<String, Integer> TABLE = buildTable();.
final is not immutable
final stops you from reassigning the field. It doesn't stop anyone from changing the object the field refers to:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NotImmutable {
static final List<String> COLORS = new ArrayList<>(List.of("red", "green"));
static final int[] PRIMES = {2, 3, 5, 7};
public static void main(String[] args) {
// COLORS = new ArrayList<>(); // error: the reference is final
COLORS.add("blue"); // fine: the list itself is mutable
PRIMES[0] = 4; // fine: array elements are mutable
System.out.println(COLORS);
System.out.println(Arrays.toString(PRIMES));
}
}
[red, green, blue]
[4, 3, 5, 7]
A public static final array or mutable collection is a real bug: any code anywhere can change your "constant". Use immutable types instead:
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Immutable {
static final List<String> COLORS = List.of("red", "green", "blue");
static final Set<String> ADMINS = Set.of("alice", "bob");
static final Map<String, Integer> HTTP_PORTS = Map.of("http", 80, "https", 443);
private static final int[] PRIMES_ARRAY = {2, 3, 5, 7};
static final List<Integer> PRIMES = List.of(2, 3, 5, 7);
// if you must expose an array, hand out a copy
static int[] primes() {
return PRIMES_ARRAY.clone();
}
public static void main(String[] args) {
System.out.println(COLORS + " " + ADMINS.contains("bob") + " " + HTTP_PORTS.get("https"));
int[] p = primes();
p[0] = 4;
System.out.println("copy changed: " + p[0] + ", original: " + primes()[0]);
try {
COLORS.add("pink");
} catch (UnsupportedOperationException e) {
System.out.println("COLORS.add: " + e);
}
try {
PRIMES.set(0, 4);
} catch (UnsupportedOperationException e) {
System.out.println("PRIMES.set: " + e);
}
}
}
[red, green, blue] true 443
copy changed: 4, original: 2
COLORS.add: java.lang.UnsupportedOperationException
PRIMES.set: java.lang.UnsupportedOperationException
List.of, Set.of and Map.of are covered in Collection Factory Methods. Note that List.of makes the list immutable, not the elements in it. A list of mutable objects can still have its elements changed.
Many style guides, including Google's Java style guide, use UPPER_SNAKE_CASE only for fields that are static final and deeply immutable. By that rule, static final List<String> COLORS = List.of(...) is a constant, while a static final ArrayList or a static final Logger is not, and gets a lower camel case name.
Where to put constants
Next to the code that uses them
The best place for a constant is usually the class that uses it, as a private static final field. Only move it somewhere shared when several classes need it.
A constants holder class
For constants shared across a package or application, use a final class with a private constructor so nobody can instantiate or subclass it:
package com.example.app;
import java.time.Duration;
public final class Http {
private Http() {} // no instances
public static final int OK = 200;
public static final int NOT_FOUND = 404;
public static final String CONTENT_TYPE = "Content-Type";
public static final Duration TIMEOUT = Duration.ofSeconds(30);
}
Callers write Http.OK, or use a static import if they use the constants a lot:
package com.example.app;
import static com.example.app.Http.NOT_FOUND;
import static com.example.app.Http.OK;
public class Main {
static String describe(int status) {
return switch (status) {
case OK -> "ok";
case NOT_FOUND -> "not found";
default -> "status " + status;
};
}
public static void main(String[] args) {
System.out.println(describe(200) + ", " + describe(404) + ", " + describe(500));
System.out.println(Http.CONTENT_TYPE + ", timeout " + Http.TIMEOUT);
}
}
$ javac -d out com/example/app/*.java
$ java -cp out com.example.app.Main
ok, not found, status 500
Content-Type, timeout PT30S
Group constants by meaning (Http, Limits, Units), not into one giant Constants class that everything depends on.
Avoid the constant interface
Fields declared in an interface are implicitly public static final, so people used to write interfaces that hold nothing but constants and then implements them to use the short names:
public class ConstantInterface {
interface Units { // anti-pattern: an interface used only for constants
double CM_PER_INCH = 2.54; // implicitly public static final
}
static class Ruler implements Units {
double toCm(double inches) {
return inches * CM_PER_INCH;
}
}
public static void main(String[] args) {
Ruler r = new Ruler();
System.out.println(r.toCm(10));
System.out.println(r instanceof Units); // true: now part of Ruler's public type
System.out.println(Ruler.CM_PER_INCH); // the constant leaks through the class
}
}
25.4
true
2.54
Implementing an interface means "is a kind of". Ruler is not a kind of Units, but now every Ruler is instanceof Units, every subclass inherits the names, and you can't remove the interface later without breaking clients. Use a holder class with static imports instead. Some old JDK classes, such as javax.swing.SwingConstants, use this pattern. Don't copy it.
Use an enum for a fixed set of related values
A group of int constants that mean "one of these options" isn't type-safe:
public class IntConstants {
static final int SIZE_SMALL = 0;
static final int SIZE_MEDIUM = 1;
static final int SIZE_LARGE = 2;
static final int COLOR_RED = 0;
static int priceCents(int size) {
return 300 + size * 50;
}
public static void main(String[] args) {
System.out.println(priceCents(SIZE_LARGE));
System.out.println(priceCents(COLOR_RED)); // compiles, but makes no sense
System.out.println(priceCents(42)); // compiles too
}
}
400
300
2400
An enum turns those values into a type the compiler checks. Each enum constant can also carry its own data:
public class EnumConstants {
enum Size {
SMALL(300), MEDIUM(350), LARGE(400);
final int priceCents;
Size(int priceCents) {
this.priceCents = priceCents;
}
}
static int priceCents(Size size) {
return size.priceCents;
}
public static void main(String[] args) {
System.out.println(priceCents(Size.LARGE));
for (Size s : Size.values()) {
System.out.println(s + " " + s.ordinal() + " " + s.priceCents);
}
System.out.println(Size.valueOf("MEDIUM").priceCents);
}
}
400
SMALL 0 300
MEDIUM 1 350
LARGE 2 400
350
priceCents(42) no longer compiles, you can iterate over all values, and you can parse them from strings. See Enums and Enums with constructors for more.
Constants in switch
A case label must be a compile-time constant (or an enum constant, or a pattern). That's one more reason the distinction between compile-time constants and other finals matters:
public class SwitchErr {
static final Integer OK = 200;
static String describe(int status) {
return switch (status) {
case OK -> "ok";
default -> "other";
};
}
}
SwitchErr.java:6: error: constant expression required
case OK -> "ok";
^
1 error
Change Integer to int and it compiles. A String constant works as a case label too.
Local constants and effectively final variables
final works on local variables as well. A final local with a constant initializer is a constant variable, just like a field:
import java.util.List;
public class Locals {
public static void main(String[] args) {
final int limit = 3; // a constant variable: final + constant initializer
final String label; // blank final: assigned exactly once below
if (args.length > 0) {
label = args[0];
} else {
label = "items";
}
int max = 2; // effectively final: never reassigned
List<String> names = List.of("ann", "bob", "cid", "dan");
names.stream()
.filter(n -> n.compareTo("b") > 0)
.limit(max)
.forEach(n -> System.out.println(label + ": " + n));
byte small = limit * 40; // OK: limit is a constant, 120 fits in a byte
System.out.println(small);
switch (args.length) {
case limit -> System.out.println("three args");
default -> System.out.println(args.length + " args");
}
}
}
$ java Locals.java
items: bob
items: cid
120
0 args
$ java Locals.java a b c
a: bob
a: cid
120
three args
Things to notice:
labelis a blank final: declared without a value and assigned exactly once on every path. The compiler checks this.maxisn't declaredfinal, but it is never reassigned, so it is effectively final. Lambdas and inner classes can only capture final or effectively final locals. See Java Closures with lambda expressions.byte small = limit * 40;compiles without a cast only becauselimitis a constant and the result fits in abyte. With a non-finalint limityou would get "possible lossy conversion".case limitworks for the same reason.
Local constants are usually written in lower camel case. UPPER_SNAKE_CASE is for static final fields.
Constants in the JDK
The JDK defines many constants you should use instead of writing the numbers yourself:
public class Builtins {
public static void main(String[] args) {
System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE);
System.out.println("Integer.MIN_VALUE = " + Integer.MIN_VALUE);
System.out.println("Long.MAX_VALUE = " + Long.MAX_VALUE);
System.out.println("Double.MAX_VALUE = " + Double.MAX_VALUE);
System.out.println("Double.MIN_VALUE = " + Double.MIN_VALUE);
System.out.println("Math.PI = " + Math.PI);
System.out.println("Math.E = " + Math.E);
System.out.println("Math.TAU = " + Math.TAU);
System.out.println("Integer.BYTES = " + Integer.BYTES);
System.out.println("Long.SIZE = " + Long.SIZE);
System.out.println("Integer.MAX_VALUE + 1 = " + (Integer.MAX_VALUE + 1));
}
}
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
Long.MAX_VALUE = 9223372036854775807
Double.MAX_VALUE = 1.7976931348623157E308
Double.MIN_VALUE = 4.9E-324
Math.PI = 3.141592653589793
Math.E = 2.718281828459045
Math.TAU = 6.283185307179586
Integer.BYTES = 4
Long.SIZE = 64
Integer.MAX_VALUE + 1 = -2147483648
Two catches:
Double.MIN_VALUEis the smallest positivedouble, not the most negative one. The most negative is-Double.MAX_VALUE.- Integer arithmetic on constants wraps silently, even when the compiler does it:
Integer.MAX_VALUE + 1isInteger.MIN_VALUE. UseMath.addExactwhen overflow should be an error.
Other useful constants: BigDecimal.ZERO and BigInteger.ONE, Duration.ZERO, StandardCharsets.UTF_8, TimeUnit values and File.separator (though Path makes it rarely needed).
Lazy constants with StableValue
A static final field is computed when the class is initialized, even if the program never uses it. For an expensive value you can delay the work with the holder class idiom. JDK 25 adds a preview API for this, StableValue (JEP 502). It computes the value once, on first use, in a thread-safe way, and the JIT then treats it as a constant:
import java.util.function.Supplier;
public class Lazy {
static String loadConfig() {
System.out.println("loading config...");
return "db=prod";
}
// computed on first get(), then treated as a constant by the JIT
static final Supplier<String> CONFIG = StableValue.supplier(Lazy::loadConfig);
public static void main(String[] args) {
System.out.println("start");
System.out.println(CONFIG.get());
System.out.println(CONFIG.get());
}
}
$ java --enable-preview --source 25 Lazy.java
start
loading config...
db=prod
db=prod
It is a preview feature: you need --enable-preview, and the API may change in later JDKs (it is being reworked as LazyConstant). For production code on JDK 25, the holder class idiom is the safe choice.
Summary
- A constant is a
static finalfield, named inUPPER_SNAKE_CASE. - A
finalprimitive orStringwith a constant initializer is a compile-time constant. Its value is copied into every class that uses it, so changing it requires recompiling those classes. Don't make values that may change intopubliccompile-time constants. - Compile-time constants can be used as
caselabels, enable narrowing assignments, and don't trigger class initialization. finalfreezes the reference, not the object. UseList.of,Set.of,Map.ofand immutable types, and never expose apublic static finalarray.- Keep constants
privatenext to the code that uses them. Share them through afinalholder class with a private constructor, not a constant interface. - Use an enum, not a group of
intconstants, for a fixed set of options.