final and Initialization Requirements
What you'll learn: How and when you must initialize final variables in Java.
The One-Time Rule
When you declare a variable as final, you're making a promise: this variable will hold exactly one value for its entire lifetime. Java enforces this promise strictly—you must initialize a final variable exactly once, and you cannot leave it uninitialized.
Think of it like carving your name into wet concrete. You get one chance to write it before the concrete hardens forever. After that, no changes are possible.
Where You Can Initialize final Variables
Java gives you two opportunities to initialize a final variable:
- At declaration: Assign the value immediately when you declare it
- In a constructor: For instance variables only (we'll cover constructors later in the course)
For local final variables (declared inside methods like main), you must either initialize them at declaration or assign them before you use them—but only once.
Examples
final int x = 10; // Initialized at declaration - valid
final int y; // Declared but not initialized
y = 20; // First (and only) assignment - valid
final int z; // Declared but not initialized
z = 5; // First assignment
z = 10; // ERROR: Cannot assign a value to final variable z
final int w; // Declared but not initialized
int result = w; // ERROR: Variable w might not have been initialized
Key Takeaway: A final variable must be initialized exactly once—either at declaration or before first use—and can never be reassigned afterward. Java's compiler will catch violations at compile-time.