JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

blank final variable in Java and How to use a blank final variable in Java with Example

What is blank final variable in Java

Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized in a constructor. Java compiler will complain if a blank final variable is not initialized during construction. If you have more than one constructor or overloaded constructor in your class then blank final variable must be initialized in all of them, failing to do so is a compile-time error in Java. Alternatively, you can use constructor chaining to call one constructor from other using this keyword, in order to delegate initialization of blank final variable in Java. In this Java tutorial, we will see What is blank final variable in Java and a code example on How to use a blank final variable.


How to use a blank final variable in Java with Example
What is a blank final variable in Java with an example? The blank final variable is like any other final variable but must be initialized in the constructor as shown in below example. If you don't initialize or forget to initialize blank final variable then the compiler will complain about it by throwing compile time error. the static and final variable is treated as a compile-time constant and their value is replaced during compile time only.


How to use a blank final variable in Java

public class BlankFinalVariable {

    private final int blankFinalVariable; //must be initialized in a constructor
 
    public BlankFinalVariable(){
        this(6); // this is Ok
        //this.blankFinalVariable = 3;
    }
 
    public BlankFinalVariable(int number){
        this.blankFinalVariable = number;
    }
 
    public static void main(String args[]) {
        BlankFinalVariable clazz = new BlankFinalVariable();
        System.err.println("Value of blank final variable in Java : " + clazz.blankFinalVariable);
    }
 
 
}

Output:
Value of blank final variable in Java : 6
Output:
Value of blank final variable in Java : 6

.