Blank Final variable in Java with examples

When a variable is declared as final, it can be assigned a value only once and cannot be updated or changed. A blank final variable in Java is a final variable which is not assigned any value when it is declared. Instead, it is initialized later. In the following example, variable var1 is a final variable and var2 is a blank final variable.

final int var1 = 30;
final int var2;
var2 = 30;

In this tutorial, Let’s study how we can use the blank final variable in Java programs with some examples.

When we declare a variable as final in a class and do not initialize it there, we use constructors to initialize it. See the following example to better your understanding of the concept.

class BlankFinal{
    final int var1;
    
    BlankFinal(int var2){
        var1 = var2;
    }
}

class Example{
    public static void main(String args[]){
        BlankFinal obj = new BlankFinal(12);
        System.out.println(obj.var1);
    }
}

Output:

12

In the above example, we have declared var1 as a blank final variable. A constructed has been used for its initialization as you can see in the program.

The compiler will throw an error if we do not initialize a blank final variable. In case we have more than one constructor in a class, then we must initialize the blank final variable in each constructor. We can also use constructor chaining to achieve this.

In the following example, we have two constructors for the BlankFinal class. We have used constructor chaining to initialize the given blank final variable. Have a look at the code and its output.

class BlankFinal{
    final int var1;
    
    BlankFinal(int var2){
        var1 = var2;
    }
    
    BlankFinal(){
        this(12);
    }
}

class Example{
    public static void main(String args[]){
        BlankFinal obj1 = new BlankFinal(12);
        System.out.println(obj1.var1);
        
        BlankFinal obj2 = new BlankFinal();
        System.out.println(obj2.var1);
        
    }
}

Output:

12
12

Thank you.

Also read: How to call one constructor from another in Java

Leave a Reply