Why Java wouldn't allow initialization of static final variable in a constructor?

JavaObject Oriented ProgrammingProgramming

If you declare a variable static and final you need to initialize it either at declaration or, in the static block. If you try to initialize it in the constructor, the compiler assumes that you are trying to reassign value to it and generates a compile time error −

Example

 Live Demo

class Data {
   static final int num;
   Data(int i) {
      num = i;
   }
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of the constant: "+Data.num);
   }
}

Compile time error

ConstantsExample.java:4: error: cannot assign a value to final variable num
   num = i;
   ^
1 error

To make this program work you need to initialize the final static variable in a static block as −

Example

 Live Demo

class Data {
   static final int num;
   static {
      num = 1000;
   }
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of the constant: "+Data.num);
   }
}

Output

value of the constant: 1000
raja
Published on 15-Oct-2019 10:05:44
Advertisements