Assigning values to static final variables in java

Object Oriented ProgrammingJava8Java Programming

In java, a non-static final variable can be assigned a value at two places.

  • At the time of declaration.

  • In constructor.

Example

Live Demo

public class Tester {
   final int A;
   //Scenario 1: assignment at time of declaration
   final int B = 2;

   public Tester() {
      //Scenario 2: assignment in constructor
      A = 1;
   }

   public void display() {
      System.out.println(A + ", " + B);
   }

   public static void main(String[] args) {        
      Tester tester = new Tester();
      tester.display();
   }
}

Output

1, 2

But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places.

  • At the time of declaration.

  • In static block.

Example

Live Demo

public class Tester {
   final int A;
   //Scenario 1: assignment at time of declaration
   final int B = 2;

   public Tester() {
      //Scenario 2: assignment in constructor
      A = 1;
   }

   public void display() {
      System.out.println(A + ", " + B);
   }

   public static void main(String[] args) {        
      Tester tester = new Tester();
      tester.display();
   }
}

Output

1, 2

The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once.

raja
Published on 23-Jul-2018 09:11:35
Advertisements