← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 11 of 12

Java Constants

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.