In the previous topic, we learned about variables. A variable stores a value, and that value can be changed while the program is running.
But what if we have a value that should never change?
For example, the value of π, the number of days in a week, or a fixed tax rate. We don't want someone to accidentally change these values in our program. For this purpose, Java provides constants.
A constant is simply a value that we decide should remain unchanged after it has been assigned.
Creating a Constant in Java
In Java, we use the final keyword to create a constant.
For example:
final int DAYS_IN_WEEK = 7;
Here, DAYS_IN_WEEK is a constant. Once we assign 7 to it, we cannot change its value later.
For example, this is valid:
final int DAYS_IN_WEEK = 7;
System.out.println(DAYS_IN_WEEK);
But this is not allowed:
final int DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 8; // Error
Java will give us an error because a final variable cannot be assigned another value.
Why Do We Need Constants?
Constants are useful when a value should remain the same throughout the program.
Imagine you are building a program that calculates the area of a circle. The value of π should not randomly change somewhere in your program.
Instead of writing:
double pi = 3.14159;
we can make it a constant:
final double PI = 3.14159;
Now, if we accidentally try to change PI, Java will prevent us from doing so.
Constants also make programs easier to understand. When you see PI, you immediately know what that value represents.
Naming Constants
There is a common naming convention for constants in Java: use uppercase letters and separate multiple words with underscores.
For example:
final int MAX_SPEED = 120;
final double PI = 3.14159;
final int DAYS_IN_WEEK = 7;
This isn't a requirement for Java to work, but it is a widely followed convention and makes constants easy to recognize.
For comparison, normal variables are commonly written like this:
int studentAge = 20;
double productPrice = 500.0;
While constants are usually written like this:
final int MAX_AGE = 100;
final double TAX_RATE = 18.0;
Constant Value Cannot Be Changed
Let's look at a simple example:
class Main {
public static void main(String[] args) {
final double PI = 3.14159;
System.out.println(PI);
}
}
The output is:
3.14159
Now imagine that somewhere later in the program we try:
PI = 3.14;
Java will produce an error because PI has been declared as final.
This is the main difference between a normal variable and a constant.
int age = 20;
age = 21; // Allowed
final int DAYS = 7;
DAYS = 8; // Not allowed
Variable vs Constant
The difference is quite simple:
Variable | Constant |
|---|---|
Value can be changed | Value cannot be changed |
Usually declared normally | Uses |
Example: | Example: |
So whenever you have a value that should stay fixed, using final can protect it from accidental changes.