Java Constants
In this page:
The final Keyword
Marking a variable final locks its value after the first assignment -- any later attempt to reassign it is a compile-time error, which is exactly the safety guarantee you want for values that should never change.
Example: The final Keyword
public class Main {
public static void main(String[] args) {
final int MAX = 10;
// MAX = 20; // ILLEGAL - compile-time error, final can't be reassigned
System.out.println(MAX);
}
}
Login to try C/C++/Java/PHP code in the editor
Static Constants
Adding static alongside final (static final int MAX_USERS = 100;) means the constant belongs to the class itself rather than any individual object, so every instance shares that one single value instead of each getting its own copy.
Example: Static Constants
public class Main {
static final int MAX_USERS = 100; // belongs to the class, shared by every instance
public static void main(String[] args) {
System.out.println(Main.MAX_USERS);
}
}
Login to try C/C++/Java/PHP code in the editor
Constant Naming Conventions
The ALL_CAPS_WITH_UNDERSCORES convention (like MAX_LIMIT) is purely stylistic, but it's so universal in Java code that spotting one instantly tells a reader 'this value is fixed' without needing to check its declaration.
Example: Constant Naming Conventions
public class Main {
static final int MAX_LIMIT = 50; // ALL_CAPS_WITH_UNDERSCORES signals "this is fixed"
public static void main(String[] args) {
System.out.println(MAX_LIMIT);
}
}
Login to try C/C++/Java/PHP code in the editor
Dynamic Initialization of Constants
A final variable doesn't have to be assigned a literal at declaration time -- it can be computed from a method call or expression at runtime, as long as it's assigned exactly once before it's ever read.
Example: Dynamic Initialization of Constants
public class Main {
static int computeLimit() { return 42; }
public static void main(String[] args) {
final int limit = computeLimit(); // computed at runtime, assigned exactly once
System.out.println(limit);
}
}
Login to try C/C++/Java/PHP code in the editor
Constant Best Practices
Grouping constants near the top of a class (or in a dedicated constants class) means anyone tuning a limit or threshold later knows exactly where to look, rather than hunting through scattered magic numbers.
Example: Constant Best Practices
public class Main {
static final int MAX_USERS = 100;
static final int MIN_AGE = 18;
// Constants grouped at the top of the class instead of scattered as magic numbers
public static void main(String[] args) {
System.out.println(MAX_USERS + " " + MIN_AGE);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: