Engineering Full Stack Apps with Java and JavaScript
A block is a group of zero or more statements between balanced braces ('{' and '}') and can be used anywhere a single statement is allowed inside a class, and this includes inside the class outside all methods and within methods. A method can also be considered as a block with a name.
Variables declared inside a block has a scope and lifetime limited to that block. For example, if you declare a variable myVar inside a method, it is local to that method and won't be recognized outside. A variable declared in one block will be available to its inner blocks, but not to its outer blocks.
When a block (without name) appears outside all methods, but inside the class, it is called an initialization block. An initialization block can be used to initialize a class similar to constructors. A constructor is the primary way to initialize an object and is executed when an object is created. We will see constructors in detail next. Initialization blocks can be static or instance initialization blocks based on if the static keyword is there or not.
Instance initialization blocks are initialization blocks without the static keyword. As we have seen, an initialization block is a block which is outside all methods, but inside a class.
Example for a normal initialization block:
class MyClass
{
// Below block is an initialization block
{
/*some code*/
}
/*some code*/
}
Instance initialization blocks can initialize final variables.
Constructors can initialize final variables.
Both instance initialization blocks and constructors cannot initialize static final variables.
All the init blocks will be executed in the order they appear, but before the constructor.
Initialization blocks and constructors are executed after the execution of initializers and hence will override any variable values assigned through an initializer.
Static initialization blocks are similar to instance initialization blocks, but has a static keyword before the block. Static Initialization blocks run only once when the class is first loaded. All static init blocks will be executed in the order they appear.
Example for a static initialization block:
class MyClass
{
//Below block is a static initialization block
static
{
/*some code*/
}
/*some code*/
}
Static initialization blocks can initialize static final variables.