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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Of course static final variables are given default values, see for example this:
The output is:
If
xwasn’t given the default value of0as 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:
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.