What is a blank final variable in Java and how do you initialise it?
A blank final is a final field declared without a value. It must be assigned exactly once, in every constructor for an instance field or in a static block for a static one, otherwise the code does not compile.
Explain it simply
A blank final is like a form with a "name" field that stays empty at first, but once you write it with a permanent pen in the admission office, you cannot change it. You get one chance, and you must use it before the form is submitted.
Example
class Ticket {
private final int pnr; // blank final instance field
static final double GST; // blank final static field
static { GST = 0.18; } // assigned once in static block
Ticket(int pnr) {
this.pnr = pnr; // assigned once in the constructor
}
int getPnr() { return pnr; }
// void change() { pnr = 5; } // compile error
}
Ticket t = new Ticket(4521);
System.out.println(t.getPnr()); // prints: 4521 (fixed for the object's life)What to say in the interview
"A final field must be definitely assigned: at declaration, in an instance initialiser block, or in each constructor. If the class has several constructors, each of them must assign it. A static final one is assigned in a static block. This lets each object have its own fixed value, like an order id, which a constant with a literal value cannot. Because of the guarantee in the Java memory model, final fields set in a constructor are safely visible to other threads."
Common mistakes
- Assigning a final field in a regular method.
- Leaving one constructor path without assigning it.