Java
static final
Learn to define constants with static final.
static final
A constant is a value that does not change throughout the program. In Java constants are defined with the static final keywords. static provides a single copy at the class level; final ensures the value cannot be changed.
Example: class Settings { static final int MAX_USERS = 100; }. Here MAX_USERS is a constant. It takes the value 100 when the class loads and cannot be changed afterwards. If you write Settings.MAX_USERS = 200; you get a compile error. Constants let you manage values used in multiple places from a single point. When the value changes, only the definition is updated; all usage points are automatically affected.
Why use constants?
Constants manage values used repeatedly in a program under a single name. When the value changes, only the constant definition is updated; all usage points are automatically updated. This eases maintenance and reduces errors.
Example: Suppose a game has static final int MAX_LIVES = 3;. If this constant is used in ten places, changing the maximum lives to 5 requires updating only the single definition. Without a constant, you would have written 3 in ten places and would need to find and update each one for a change. Constants also improve code readability; MAX_LIVES is more meaningful than 3.
Exercise Add constants to Settings
Define a class Settings. Add a static final int MAX_USERS = 100 constant. Add a static final String APP_NAME = "Library" constant. In main print both constants' values on separate lines.
Show example solution
class Settings {
static final int MAX_USERS = 100;
static final String APP_NAME = "Library";
public static void main(String[] args) {
System.out.println(Settings.MAX_USERS);
System.out.println(Settings.APP_NAME);
}
}
Test yourself
-
What does final provide in: static final int MAX = 10;?
- The value is accessible everywhere
- The value cannot be changed
- The value becomes static
- The value is deleted
Show answer
The value cannot be changed — final ensures the value cannot be changed.
-
Complete the constant definition
class Settings {
____ int MAX_USERS = 100;
}
Show answer
class Settings {
static final int MAX_USERS = 100;
}
-
Match the constant parts
- static
- Class level
- final
- Immutability
- MAX_USERS
- Constant name
- 100
- Value
Next lesson: Uppercase convention