In Java, the final keyword makes variables immutable (unchangeable). Normally, you initialize a final variable at declaration time (e.g. final int MAX = 100;). However, Java also supports **Blank Final Variables**—final variables that are declared without an initial value.
A blank final variable **must be initialized inside the constructor** of the class. If you fail to initialize it, the compiler throws an error. Once initialized, it freezes and cannot be changed.
Imagine you run a trophy workshop. You purchase **blank trophies (blank final variables)** from the supplier. They have no name engraved on them yet.
When a customer orders a trophy, you bring it into the **assembly workshop (the constructor)**. There, you engrave the winner's name on it. Once the trophy leaves the workshop, the name is carved in metal and sealed. It can **never be changed again**.
Java Implementation
In this class, MAX_SIZE is a blank final variable. It is initialized in both overloaded constructors but cannot be modified inside the finals() method:
package io.practise;
class Serialisehasa {
// Declaring a Blank Final variable
final int MAX_SIZE;
// Constructor 1: Default
Serialisehasa() {
MAX_SIZE = 10; // Initialize here
System.out.println("Default MAX_SIZE: " + MAX_SIZE);
}
// Constructor 2: Overloaded
Serialisehasa(int a) {
MAX_SIZE = a; // Or initialize here
System.out.println("Custom MAX_SIZE: " + MAX_SIZE);
}
public static void main(String[] args) {
Serialisehasa f = new Serialisehasa();
Serialisehasa f1 = new Serialisehasa(20);
f1.finals();
}
void finals() {
// MAX_SIZE = 90; // COMPILER ERROR: Cannot assign a value to final variable 'MAX_SIZE'
System.out.println("Current value: " + MAX_SIZE);
}
}
Conclusion
Blank final variables are useful when you want to establish immutable configuration parameters that depend on constructor input parameters passed at runtime instantiation.