Assigning values to static final variables in Java


Assigning values to static final variables in Java:
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.

For example, following program works fine.

class Test {
  final int i;  // i could be assigned a value here also
  Tets() {
    i = 10;

  //other stuff in the class

If we make i as static final then we must assign value to i with the delcaration.

class Test {
  static final int i = 10;  // Since i is static final, it must be assigned value here only. 

  //other stuff in the class

Such behavior is obvious as static variables are shared among all the objects of a class; creating a new object would change the same static variable which is not allowed if the static variable is final.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

1.3 Average Difficulty : 1.3/5.0
Based on 32 vote(s)