- Where have you mostly used the initialization block?
- Can you use these to assign values to static instance variables?
- How is this different from assigning using a constructor?
- My book says that the initialization block is executed when the “class is loaded”. What does loading a class mean?
Additional Question
Which is better?
class {static final instance-variable = val}
or
class {static final instance-variable; static {instance-variable=val}}
An initialization block is always called regardless of the constructor you’d like to use. So, if the class in question has more than one constructor and you’d like to run some code regardless of the constructor used, then use an initialization block.
However, when used to assign default values, I’d just assign them directly. If they are even constants, then I’d add
finalto the list of modifiers as well.Update since you drastically changed the question, here’s a renewed answer:
To execute some code regardless of the constructor used.
You’ll need a
staticinitializer block.This has the benefit that you can do more than just assigning a value. E.g. getting it from some method and handling the exception:
It’s always assigned regardless of the constructor used.
The book is actually talking about a static initialization block. A class is usually loaded when you reference it for the first time in your code. You can also forcibly load it by
Class#forName()(such as you do with JDBC drivers). I’ve posted an answer with more examples and explanation before here.Hope this helps.