Java Constants
Sometimes a value should never change once it is set, such as a tax rate, the number of days in a week, or a mathematical constant. In Java you protect a value like this with the final keyword, which turns an ordinary variable into a constant.
Making a value final
Add the word final in front of a variable declaration and Java guarantees the value can be assigned only once. Any later attempt to change it is caught by the compiler, before your program ever runs, which turns a whole class of accidental bugs into simple build errors.
Declaring a constant
public class Main {
public static void main(String[] args) {
final int DAYS_IN_WEEK = 7;
System.out.println(DAYS_IN_WEEK);
}
}If you try to reassign a final variable, the code simply will not compile. This is exactly the safety net you want for a value that is meant to stay fixed.
This will not compile
public class Main {
public static void main(String[] args) {
final double PI = 3.14159;
PI = 3.14; // error: cannot assign a value to final variable PI
}
}Naming constants
By long-standing Java convention, constants are written in uppercase letters with underscores between words. This makes them instantly recognisable in the middle of ordinary code and signals to other developers that the value is not meant to move.
Class-level constants
Constants that belong to the whole class, rather than a single method, are usually declared as static final. The static part means there is one shared copy for every object, and the final part means it cannot change. This is the standard pattern for shared settings like limits and rates.
A shared class constant
public class Main {
static final double SALES_TAX = 0.08;
public static void main(String[] args) {
double price = 50.0;
double total = price + price * SALES_TAX;
System.out.println("Total: " + total);
}
}Why bother with constants
- A named constant explains what a number means, so 0.08 becomes the far clearer SALES_TAX.
- If the value ever needs updating you change it in one place instead of hunting through the whole file.
- The compiler stops anyone, including future you, from changing it by mistake.
- Constants make code easier to read and to review.