Why aren't static final variables given default values, whereas static (but non-final variables are given default values).
What is the reason that such behavior was implemented in Java?
The default value of static variable is zero. The static variables are alive till the execution of the program.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
No, local variables do not have default values. Once we create a local variable we must initialize it before using it. Since the local variables in Java are stored in stack in JVM there is a chance of getting the previous value as default value. Therefore, In Java default values for local variables are not allowed.
Of course static final variables are given default values, see for example this:
class Test {
static final int x;
static {
printX();
x = 42;
printX();
}
static void printX() {
System.out.println("Here x is "+x);
}
public static void main(String[] args) { }
}
The output is:
Here x is 0
Here x is 42
If x
wasn't given the default value of 0
as specified in JLS 4.12.5, the output would depend on the JVM used. You might see some random number.
Update: Now that we have demonstrated that static final fields do get a default value, you may want to know why the default value is not enough. There is no good answer to that question, besides the obvious one: "The spec says so". Excerpt from 8.3.1.2:
It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.
We can only guess at the motivation behind such a restriction, but I think it's to make programs easier to understand. If you want to set the variable to 0 it's clearer to do it explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With