What is a blank uninitialized final variable in java?


A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed. So, the state of the object can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.

Therefore, once we declare a final variable it is mandatory to initialize the final variable at the time of declaration or using constructor.

If not, a compile time error may occur saying “The blank final field num may not have been initialized”.

Example

public class Test{
   final int num;
   
   public static void main(String args[]){
      Test t = new Test();
      System.out.println(t.num);
   }
}

Error

C:\Sample>javac Test.java
Test.java:2: error: variable num not initialized in the default constructor
final int num;
^
1 error

Updated on: 02-Sep-2022

895 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements