Java Interview Question #3 : Can Java have blank final Value ?

Que 3. Can Java have blank final Value ?

Answer : No

package com.c4learn.inheritance;
public class BlankFinalValue {
    final int myValue;
    public BlankFinalValue(){
    	this.myValue = 3;
    }
    public static void main(String[] args) {
    	BlankFinalValue s1 = new  BlankFinalValue();
    }
}

Output :

Compiler Successfully

Explanation :

  1. We cannot have final Value which is uninitialized.
  2. You will get compile time error if you did not provide initialization.
  3. In this case we have to provide initialization in the constructor. (As shown in above program)

If final variable is not initialized in the constructor then it will throw compile time error as below -

Uninitialized Final Value

If You have Multiple Constructor then -

we need to initialize final variable in each of the constructor like below program -

package com.c4learn.inheritance;
public class BlankFinalValue {
    final int myValue;
    public BlankFinalValue(){
    	this.myValue = 3;
    }
    public BlankFinalValue(int num){
    	this.myValue = num;
    }
    public static void main(String[] args) {
    	BlankFinalValue s1 = new  BlankFinalValue();
    }
}

If you failed to initialize final variable in any of the constructor then you will get compile time error -

The blank final field myValue may not have been initialized