Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed. Initialization Blocks come in two flavours:
- Static Initialization Blocks: Runs first when the class is first loaded. Declared by using the keyword “Static”
- Instance Initialization Blocks: Runs every time when the instance of the class is created.
static int y;
//Static Initialization Block
// Instance Initialisation Block
Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run. The order in which initialization blocks appear in a class matters. If a class has more than one they all run in the order they appear in the class file.
Some rules to remember:
- Initialization blocks execute in the order they appear.
- Static Initialization blocks run once when the class is first loaded.
- Instance Initialization blocks run every time a class instance is created.
- Instance Initialization blocks run after the constructor’s call to super().
“Hello World” program in Java without ever using a main method-
public class Hello
//Static Initialisation Block
No related posts.
Connect to us …
- Book Review: Murach’s Java Servlets And JSP 3rd Edition September 23, 2014
- Book Review: RESTful Web Services with Dropwizard by Alexandros Dallas September 8, 2014
- Book Review: RabbitMQ Essentials by David Dossot September 7, 2014
- Parameterized Test Runner in JUnit August 25, 2014
- Simple Aspect Oriented Programming (AOP) using CDI in JavaEE August 24, 2014
Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for your support.