Constants in Java
Learn how to declare constants in Java using the final keyword, including local constants, static final class constants, blank final fields, naming conventions, constants in interfaces, and common mistakes.
Introduction
In the previous lesson, you learned about variables — named storage locations whose values can change while a program runs. But some values should never change once they are set: the value of PI, the maximum number of login attempts allowed, or the number of days in a week. Java gives you a way to protect these values from accidental modification: constants.
final double PI = 3.14159;
final int MAX_LOGIN_ATTEMPTS = 3;What is a Constant?
A constant is a variable whose value is assigned once and cannot be changed afterward. In Java, you create a constant by declaring a variable with the final keyword. Once a final variable has been assigned a value, any attempt to reassign it causes a compile-time error.
A variable can change over time. A constant is locked in place the moment it receives its value — the compiler enforces this for you, so you cannot accidentally overwrite it later in your code.
Why Constants are Needed
- They prevent accidental changes to values that must stay fixed, like tax rates or configuration limits.
- They make code more readable — MAX_USERS is clearer than a bare number like 100 scattered through your code.
- They make code easier to maintain — change the value in one place instead of hunting through the codebase.
- They communicate intent to other developers reading your code.
The final Keyword
The final keyword is what turns an ordinary variable into a constant. It can be applied to local variables, instance fields, static fields, method parameters, methods (to prevent overriding), and even classes (to prevent inheritance) — but in this lesson we focus on its use with variables.
final int MAX_SCORE = 100;
MAX_SCORE = 200; // Compile-time error: cannot assign a value to final variable MAX_SCOREDeclaring Constants
A constant is declared by placing final before the type. It is best practice — though not required by the compiler — to also declare number-like constants as static when they belong to a class, since the value is the same for every instance.
public class AppConfig {
static final int MAX_USERS = 500;
static final String APP_NAME = "PrograMinds";
static final double VERSION = 1.0;
}Naming Conventions
By strong convention, Java constants are named in UPPER_SNAKE_CASE — all uppercase letters with underscores separating words. This immediately signals to anyone reading the code that the value never changes.
| Constant | Regular Variable |
|---|---|
| MAX_USERS | maxUsers |
| TAX_RATE | taxRate |
| DEFAULT_TIMEOUT | defaultTimeout |
Local Constants
A local constant is declared inside a method and must be assigned a value at the point of declaration (or exactly once before it is used).
public void calculateArea() {
final double PI = 3.14159;
double radius = 5.0;
double area = PI * radius * radius;
System.out.println("Area: " + area);
}Static Final Class Constants
The most common way to define a constant that belongs to a whole class (rather than one object) is to mark a field both static and final. This is often called a "class constant" — there is exactly one copy shared by every instance, and it never changes.
public class Circle {
static final double PI = 3.14159;
double radius;
Circle(double radius) {
this.radius = radius;
}
double getArea() {
return PI * radius * radius;
}
}Since PI never changes and isn't tied to any single Circle object, marking it static means Java stores just one shared copy instead of duplicating it in every object — saving memory and reinforcing that it is a fixed, shared value.
Blank Final Variables
A "blank final" is a final variable that is declared without an initial value, on the condition that it is assigned exactly once — for instance fields, this is typically done inside every constructor.
public class Employee {
final String employeeId; // blank final
Employee(String employeeId) {
this.employeeId = employeeId; // assigned exactly once, here
}
}Constants in Interfaces
Any field declared inside a Java interface is implicitly public, static, and final, even if you don't write those keywords yourself. This makes interfaces a common (if old-fashioned) place to group related constants.
public interface Constants {
int MAX_USERS = 500; // implicitly public static final
String APP_NAME = "PrograMinds";
}While interfaces can hold constants, modern Java style generally prefers a final class with a private constructor, or an enum, to group related constants — reserving interfaces for defining behavior.
Constants vs Variables
| Constants | Variables |
|---|---|
| Declared with final | Declared without final |
| Value cannot change after assignment | Value can be reassigned freely |
| Named in UPPER_SNAKE_CASE | Named in camelCase |
| Usually static when tied to a class | Usually instance-level |
| Represents a fixed rule or limit | Represents changing program state |
Real-World Example
Applications commonly centralize their fixed settings into constants so that changing a single value updates behavior everywhere it is used.
public class BankAccount {
static final double MIN_BALANCE = 500.0;
static final double OVERDRAFT_FEE = 35.0;
double balance;
BankAccount(double balance) {
this.balance = balance;
}
void withdraw(double amount) {
if (balance - amount < MIN_BALANCE) {
balance -= OVERDRAFT_FEE;
System.out.println("Overdraft fee applied!");
} else {
balance -= amount;
}
}
}MIN_BALANCE and OVERDRAFT_FEE are business rules that should never change accidentally while the program runs — exactly what final static constants are for.Common Mistakes
final int MAX = 10;
MAX = 20; // Compile-time errorfinal String id; // Error if never assigned before useNaming a constant maxUsers instead of MAX_USERS still compiles, but it hides the fact that the value is fixed from anyone reading your code.
Best Practices
- Use UPPER_SNAKE_CASE for all constant names.
- Mark class-level constants as both static and final.
- Group related constants in one class or enum instead of scattering them.
- Prefer enums over plain constants when representing a fixed set of related options.
- Use constants instead of "magic numbers" directly in your code.
FAQs
Is final the same as const in other languages?
Conceptually yes — final prevents reassignment. Java does not have a const keyword for this purpose (const is reserved but unused).
Can a final variable ever change if it refers to an object?
No, the reference itself cannot be reassigned to point to a different object. However, if the object itself is mutable, its internal state can still change — final only locks the reference, not the object's contents.
Do all constants need to be static?
No. A final instance field is a constant that can differ per object (like a blank final employeeId), while static final is used when the value is shared by the entire class.
Why use constants instead of writing the number directly?
Named constants make code self-documenting and easy to update — changing MAX_USERS in one place is safer than searching for every occurrence of the number 500.
Summary
- A constant is a value that cannot change once assigned, created using the final keyword.
- Constants are conventionally named in UPPER_SNAKE_CASE.
- static final fields are class constants, shared by every instance.
- A "blank final" field can be assigned once, often inside a constructor.
- Interface fields are implicitly public static final.
- Using constants instead of magic numbers makes code clearer and easier to maintain.
- You are ready to learn about data types in Java.