static final
- Java course
- Intermediate
- Lesson 36/116
- 4 min
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.
Practice 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.
Starter code
// Define the Settings class
// Add two constants
// Print in mainSample 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);
}
}Expected output
100 Library
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does final provide in: static final int MAX = 10;?
- The value is accessible everywhere
- The value cannot be changed Correct answer
- The value becomes static
- The value is deleted
Explanation: final ensures the value cannot be changed.
2 Complete the constant definition
class Settings {
____ int MAX_USERS = 100;
}
class Settings {
static final int MAX_USERS = 100;
}
Explanation: static final defines a constant.
3 Match the constant parts
| Term | Meaning |
|---|---|
static |
Class level |
final |
Immutability |
MAX_USERS |
Constant name |
100 |
Value |