Final Constants
in Java
Learn how to declare, name, and use final constants to write safer, more readable, and maintainable Java code.
What is a Constant?
A constant is a variable whose value is assigned once and never changes during the program's execution. Think of it as a locked container: once you put something in, the lid is sealed forever.
The final Keyword
In Java, you create a constant by adding the keyword final before the variable declaration. Once assigned, any attempt to change the value causes a compile-time error.
Why Use Constants?
MAX_SPEED is clearer than the raw number 120.Syntax Rules
final before the data type.int, double, String, etc.Anatomy of a final Declaration
final vs Non-final Variables
| final Variable | Regular Variable | |
|---|---|---|
| Re-assignment | ✕ Compile error | ✓ Allowed |
| Naming convention | UPPER_SNAKE_CASE | camelCase |
| Intent | Value is a fixed fact | Value will change |
| Bug protection | High | None (can change anywhere) |
| Typical use | \( \pi \), tax rates, config | Counters, accumulators |
Local vs Class-Level Constants
static final at the class level. Shared across all instances.How to Apply Final Constants
static final at class level. Only in one method? Use local final.MAX_RETRIES, not MR.Example 1: Circle Area
Calculate the area of a circle with radius 5 using \( A = \pi r^{2} \). Instead of writing 3.14159 directly, we use a final constant.
Example 2: Sales Tax Calculator
Example 3: Game Config
Decision: final or Not?
Naming Best Practices
MAX_SPEED, DEFAULT_COLOR.INTEREST_RATE over IR. A reader should understand the constant without context.NUM_PLAYERS is clear; NP is not.Common Mistakes
double TAX = 0.08; without final. Now it can be reassigned accidentally.camelCase for constants: final int maxSize = 10; violates convention and confuses readers.MAX = 20; later in the code. This triggers a compile-time error.Question 1 of 5
Which keyword makes a variable's value unchangeable in Java?
Question 2 of 5
What is the correct naming convention for a constant in Java?
Question 3 of 5
What happens if you try to reassign a final variable?
Question 4 of 5
Which declaration creates a class-level constant accessible from anywhere?
Question 5 of 5
Consider the following code:
public class Geometry {
public static final double PI = 3.14159;
public static void main(String[] args) {
final int RADIUS = 4;
double circumference = 2 * PI * RADIUS;
RADIUS = 5; // Line X
System.out.println(circumference);
}
}
What is the result of compiling and running this code?