9.core Java Blocks
9.core Java Blocks
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in
the class body. The runtime system guarantees that static initialization blocks are called in the
order that they appear in the source code.
Example:
class Test {
static { // static block
System.out.println("Static Block 4");
}
Example:
class Test {
static { // static block
System.out.println("Static Block 1");
}
{ // instance block
System.out.println("Instance Block 1");
}
Test() {
System.out.println("0-arg Const");
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
}
Example:
class Test {
static int x;
static { // static block
x = 10;
Test.m1();
System.out.println("Static Block 1");
}
class Whatever {
public static varType myVar = initializeClassVariable();
The advantage of private static methods is that they can be reused later if we need to reinitialize
the class variable.
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
Normally, we would put code to initialize an instance variable in a constructor. There are two
alternatives to using a constructor to initialize instance variables: initializer blocks and final
methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the
static keyword:
{
// whatever code is needed for initialization goes here
}
The runtime system guarantees that instance initialization blocks are called in the order that they
appear in the source code.
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can
be used to share a block of code between multiple constructors.
Example:
class Test {
int x;
{ // instance block
x = 10;
System.out.println("Instance Block");
}
Test() {
System.out.println("0-arg Const :" + x);
}
Example:
class Test {
{ // instance block
System.out.println("Instance Block 1");
}
{ // instance block
System.out.println("Instance Block 2");
}
Test() {
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
System.out.println("0-arg Const");
}
Example:
class Test {
{ // instance block
System.out.println("Instance Block 1");
}
{ // instance block
System.out.println("Instance Block 2");
}
Test() {
System.out.println("0-arg Const");
}
Example:
class Test {
{ // instance block
System.out.println("Instance Block 1");
}
Test() {
System.out.println("0-arg Const");
}
Test(int x) {
System.out.println("1-arg Const");
}
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
}
}
[email protected] Cell: 78 42 66 47 66