Reputation: 31
Consider a static
variable, for example:
private static int x;
If we try printing its value in the main method, it will be 0. So the variable is initialised. Now consider if the variable is final
:
private static final int x;
This is not possible; why? We have to initialise it like private static final int x = 2;
, or using a static initialiser like:
static {
x = 2;
}
A static
variable is initialised by default; so why is there a compilation error if the variable is also final
?
Upvotes: 3
Views: 403
Reputation: 1326
NOTE: The static keyword on your question title can be removed because you should initialize all final variables and not only static final ones.
All final variables should be explicitly initialized or at the point of declaration or in every constructor of the class in which it is declared ( in this case it is named blank final variable ). This because a final variable value can't be changed after first assignment. So language raises warning to implicitly assignments to final variables to drive developer to explicitly assign a value ( even if it is the default one like '0' for Integers ).
Moreover in the specific case of a "static final" variable you can also assign the value in a static initializer of the class in which it is declared.
Upvotes: 0
Reputation: 41
Paragraph from Oracle Documentation: The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).
Edit: Please, check the java language specification. The answer to your question is there.
Upvotes: 0
Reputation: 51152
In principle the language could let you declare a static final
field and have it take its default value, but in practice if you fail to give an explicit value for a static final
field then it is almost always by mistake. So the compiler gives you an error here because
null
, so if using that value is what you intended, then the inconvenience imposed on you is minimal; you just have to write static final int x = 0;
instead of static final int x;
.In fact, being forced to write = 0
or = null
explicitly makes your code easier to read, understand and maintain. Keep in mind that most code will be read hundreds or thousands of times more often than it is written, so you are actually saving time by being more verbose and explicit.
Upvotes: 8