What is a blank uninitialized final variable in java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 10-Jan-2018 06:26:52
Advertisements