Close

Blank final variable in Java

[Updated: Feb 11, 2016, Created: Feb 11, 2016]

Java 

Blank final variables in Java are final variable which are not initialized while declaration.

They must be initialized in constructor otherwise there will be compile time error:

public class Test{
private final TestData testData;
public Test(TestData testData){
this.testData = testData;
}
}

final keyword ensures that a variable cannot be reassigned another value or more correctly it cannot change it's memory reference. It can change it's state though (if it's mutable).

In above example, once initialized in constructor, we cannot change testData reference, say by testData = anotherTestDataReference or by testData = new TestData() but we can change testData state by calling it's methods testData.setSomething(.....).

Blank final variable are useful to create non-optional objects, specially when the value to be assigned is dynamically decided during construction time of the object and not during class declaration.

A static final variable (compile time constants) can also be blank. In this case it must be initialized in static block:

public class Test{
private static final TestData testData;
static{
testData = new TestData();
}
}



Reference:
JLS 4.12.4

See Also