Why would I use a static block:
static {
B = 10;
}
over:
Integer B = 10;
What is the advantages/disadvantages of one over the other?
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.
You should only use a static initializer block, when it is necessary. For example, sometimes you need to do several steps to calculate the final value of the field. In this case you have two opportunities: write a method that calculates the value and declare your field as
static final Integer B = calculateB(), or use an initializer block:In this case I prefer the static block, because a method might be confusing (other developers might try to call it, although it is only meant to be called once during initialization).
The same applies for instance fields as well, although normally one would avoid the unusual initialization block and simply write the initialization logic for fields into the constructor (which is of course not possible for static fields).