The order in which initialisation blocks execute can be dificult to grasp so I present below a simple ordered list of when a block will execute.
- Static blocks: run when the class is loaded.
- The class is loaded before ANY code in the class is executed.
- Instance blocks: run when an instance is created.
- You can have as many blocks as you like of both static and instance types.
- The order that they appear in the class determines the order in which they are executed.
- Instance initialisation blocks are often used as places to put code that all constructors should execute.
- If an exception is thrown (throw new Exception()) then it must be surrounded with a try catch, otherwise it will not compile.
It is also important to know how constructor interact with initialisation blocks. See the blog on Initialisation blocks and Constructors.
Leave a Reply