Java Constants

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_RATE instead of 0.18 everywhere. Change it once, every use updates.
  • Readable. TAX_RATE tells the reader what it is; bare 0.18 means 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, locked
System.out.println(DAYS_IN_WEEK);

What final does:

  • Locks the box right after the first value goes in.
  • DAYS_IN_WEEK now holds 7 for 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

7

Now 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 value

Java will not compile this. The message looks something like this.

Output

error: cannot assign a value to final variable DAYS_IN_WEEK

The 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 yet
MAX_USERS = 100; // ✅ first and only assignment — allowed
System.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_SPEED or PI.
  • Words joined by underscores. Not camelCase: DAYS_IN_WEEK.
  • Clear meaning. TAX_RATE, not mystery names like TR.

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.14159
0.18
100

🏛️ 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:

  • final means the value cannot change. Same lock as before.
  • static means 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.53975

Java 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), final fixes the value. You cannot change it.
  • With objects, final locks the reference, not the contents. A reference is the link from your variable to the object. So final means “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 contents
System.out.println(name); // prints: Alex Smith

That 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 reference

Java 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 set
final double TAX_RATE = 0.18;
TAX_RATE = 0.20; // error: cannot assign to a final variable
// ✅ Good: set the correct value once
final 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 variable
final int maxSpeed = 120;
// ✅ Good: clearly a constant
final 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 value
final int LIMIT;
System.out.println(LIMIT); // error: variable LIMIT might not have been initialized
// ✅ Good: assign once, then use
final 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_RATE instead of 0.18 everywhere; change it once, every use updates.
  • Use static final for shared values. Class-wide constants get one shared copy.
  • Use built-in constants when they exist. Math.PI, Integer.MAX_VALUE are 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 final keyword, like final int DAYS_IN_WEEK = 7;.
  • ✅ Java blocks any attempt to change a final value, 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 final at the class level.
  • ✅ For objects, final locks 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. 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. 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. 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. 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.

Java Wrapper Classes

Share & Connect