Java Constants
Table of Contents + −
In the last lesson you learned about Java type promotion. Most variables can change any time. But some values are fixed facts that should never change: days in a week, a tax rate, the value of Pi. Java lets you lock such values, and we call them constants.
🤔 Why do we need constants?
The pain: you type 0.18 for tax in ten places. The rate goes up, you fix nine and miss one. One screen now charges the old tax, and nothing errors out.
A constant is a value you set once and lock. Why it helps:
- Protects a fixed fact. A week always has 7 days. Set it to 8 by accident and Java refuses to compile.
- One source of truth. One
TAX_RATEinstead of0.18everywhere. Change it once, every use updates. - Readable.
TAX_RATEtells the reader what it is; bare0.18means nothing. - A real lock. It is not a polite note; Java enforces it.
🔒 Making a constant with final
You make a constant by adding final in front of a normal variable. This code stores 7 and prints it.
final int DAYS_IN_WEEK = 7; // ✅ set once, lockedSystem.out.println(DAYS_IN_WEEK);What final does:
- Locks the box right after the first value goes in.
DAYS_IN_WEEKnow holds7for the rest of the program.- You still read it by name, like any variable.
Think of a normal variable as a whiteboard you can wipe; a final variable is permanent ink. The first value is the last value.
Output
7Now try to change it. This second line gives it a new value.
final int DAYS_IN_WEEK = 7;DAYS_IN_WEEK = 8; // ❌ error: cannot change a final valueJava will not compile this. The message looks something like this.
Output
error: cannot assign a value to final variable DAYS_IN_WEEKThe program never runs. The error happens at compile time, before anything starts, so this bug can never reach a real user. The lock is doing its job.
final means once, for good
A final variable can be set one time only. After that first assignment, Java blocks every change. So make sure the value you give it is the value you really want.
You can also declare it first and assign once later. This is called a blank final. The rule holds: assign it exactly one time.
final int MAX_USERS; // declared, no value yetMAX_USERS = 100; // ✅ first and only assignment — allowedSystem.out.println(MAX_USERS);A second assignment below would be rejected. Reading it before any assignment is also an error: a constant must have a value before you use it.
🏷️ Naming constants
Constants use a different naming style. It is a strong habit in Java, not a language rule, but everyone follows it so constants are easy to spot.
- All capital letters. Like
MAX_SPEEDorPI. - Words joined by underscores. Not camelCase:
DAYS_IN_WEEK. - Clear meaning.
TAX_RATE, not mystery names likeTR.
This style is called UPPER_SNAKE_CASE. Seeing it tells a reader “this is a constant, do not change it”. Three constants in that style:
final double PI = 3.14159;final double TAX_RATE = 0.18;final int MAX_USERS = 100;System.out.println(PI);System.out.println(TAX_RATE);System.out.println(MAX_USERS);Each name shouts “fixed value”. Next to a camelCase variable like playerScore, the styles differ on purpose, so in a big file your eyes tell facts from things that move.
Output
3.141590.18100🏛️ Class-level constants with static final
Often a constant belongs to the whole program, not one method. Pi is the same everywhere. For values like that, put the constant at the class level and add static. You see static final together a lot in real code. This example declares Pi at the class level, then uses it for a circle’s area.
public class Circle { static final double PI = 3.14159; // ✅ shared, fixed, class-level
public static void main(String[] args) { double radius = 5; double area = PI * radius * radius; System.out.println(area); }}Splitting the two keywords:
finalmeans the value cannot change. Same lock as before.staticmeans the value belongs to the class, not one object. There is a single shared copy.
Why static matters: without it, Java makes a fresh copy of Pi for every object you create, which is pure waste. Pi is the same for every circle. So you store it once on the class and everyone shares that copy. One Pi, shared by all.
Output
78.53975Java already has PI
You do not need to write your own Pi. Java gives you Math.PI, a ready-made, very precise constant. Use Math.PI in real code. We wrote our own here just to show how constants work.
🧱 final with primitives vs final with objects
This part surprises people, so read slowly.
- With primitives (
int,double),finalfixes the value. You cannot change it. - With objects,
finallocks the reference, not the contents. A reference is the link from your variable to the object. Sofinalmeans “always point at the same object”, not “this object can never change inside”.
Picture a house and its address. The reference is the address on paper; final means you cannot erase it and write a new one. But people inside can still rearrange the furniture, because you locked the address, not the rooms.
StringBuilder is an object whose contents can change. This code keeps the same object but edits what is inside.
final StringBuilder name = new StringBuilder("Alex");name.append(" Smith"); // ✅ allowed — we change the object's contentsSystem.out.println(name); // prints: Alex SmithThat runs fine. We edited the same object, not pointed name at a new one. The address stayed the same. Now we try to repoint the variable at a brand new object.
final StringBuilder name = new StringBuilder("Alex");name = new StringBuilder("Riya"); // ❌ error — cannot repoint a final referenceJava rejects this. Erasing the old address and writing a new one is exactly what final blocks for a reference.
final freezes the link, not the object
For objects, final stops you pointing the variable at a different object. It does not stop the object’s own contents from changing. So a final list can still have items added to it. If you want a truly unchangeable object, you need extra help, like List.of(...) for a fixed list.
Keep the split in your head: with primitives, final freezes the value; with objects, it freezes the link.
⚠️ Common Mistakes
Trying to change a final value. Once set, it is locked. Assigning again is a compile error, which is the feature working.
// ❌ Avoid: changing a final after it is setfinal double TAX_RATE = 0.18;TAX_RATE = 0.20; // error: cannot assign to a final variable
// ✅ Good: set the correct value oncefinal double TAX_RATE = 0.20;Using camelCase for constants. It compiles, but it breaks the habit and others lose the visual signal.
// ❌ Avoid: looks like a normal changing variablefinal int maxSpeed = 120;
// ✅ Good: clearly a constantfinal int MAX_SPEED = 120;Forgetting to assign a value. A final variable must get a value before you use it. Reading it before assigning is an error.
// ❌ Avoid: used before it ever got a valuefinal int LIMIT;System.out.println(LIMIT); // error: variable LIMIT might not have been initialized
// ✅ Good: assign once, then usefinal int LIMIT;LIMIT = 50;System.out.println(LIMIT);Thinking a final object is frozen inside. final on an object only locks the link; its contents can still change. A final list can still get new items.
✅ Best Practices
- Lock values that should never change. Tax rates, limits, Pi. Mark them
final. - Use UPPER_SNAKE_CASE. All caps with underscores, so constants stand out.
- Name a value once. One
TAX_RATEinstead of0.18everywhere; change it once, every use updates. - Use
static finalfor shared values. Class-wide constants get one shared copy. - Use built-in constants when they exist.
Math.PI,Integer.MAX_VALUEare precise and recognised. - Remember the object rule. If the object itself must stay fixed, use an unchangeable type, not just
final.
🧩 What You’ve Learned
Let’s recap constants.
- ✅ A constant is a value that is set once and can never change.
- ✅ You make one with the
finalkeyword, likefinal int DAYS_IN_WEEK = 7;. - ✅ Java blocks any attempt to change a
finalvalue, and it does this at compile time, before the program runs. - ✅ Constants use UPPER_SNAKE_CASE (all caps, underscores) so they stand out.
- ✅ For shared, program-wide constants, you use
static finalat the class level. - ✅ For objects,
finallocks the reference, not the contents, so the object inside can still change.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Which keyword makes a variable a constant in Java?
Why: The final keyword locks a value so it can be set once and never changed.
- 2
What happens if you try to change a final variable after it is set?
Why: Java refuses to compile any attempt to reassign a final variable. The lock is the whole point.
- 3
Which is the correct naming style for a constant?
Why: Constants use UPPER_SNAKE_CASE: all capitals with underscores between words, like MAX_SPEED.
- 4
For a final variable that holds an object, what does final actually lock?
Why: final locks the reference, so the variable always points at the same object. The object's own contents can still change.
🚀 What’s Next?
Constants store fixed primitive values, but Java also lets you treat primitive values as full objects when you need them. Next we look at the helper types that make that possible.