The
below program will illustrate the loading order of different blocks (Static and this block) and methods
when main class is invoked in Java.
----------------------------------------------- Order Test Program -----------------------------
public class OrderTest {
public static final
int
A
=5; // Static final Variables: These are constant ,
public static final
int
B; // need to initialize, once initialized will not be able
to change value
public static final
String s;
// If not initialized will be able to initialize
only from static block
{
System.out.println("This
Block ...."); // This Block : Execute Each time the when the
//
object of class is created, after the super() call
}
static {
System.out.println("
First Static Block ..."); // static Block: Execute before main
method,
//
when the class is first loaded
}
public OrderTest() {
System.out.println("Constructor
...."); //
Constructor: Execute during object creation
}
public static void
print1() {
System.out.println("Static
Method ...."); // Static
method: Execute When it is explicitly called.
}
static {
if (A==5) { B=10; s = "ab";
} // Initializing static final variables
else { B= 5; }
System.out.println("Second
Static Block ...");
System.out.println("--------A
="+A);
System.out.println("--------B
="+B);
}
static {
System.out.println("Third
Static Block ....");
// B =5; // Compilation error : Final field B already have been assigned
}
public static void
main(String[] args) {
System.out.println("Main
Block .........");
print1();
OrderTest o
= new
OrderTest();
print1();
}
}
------------------------------------
Output Of the above program ---------------------------------------------
First Static Block ...
Second Static Block ...
--------A =5
--------B =10
Third Static Block ....
Main Block .........
Static Method ....
This Block ....
Constructor ....
Static Method ....
---------------------------------End
of output -------------------------------------------------------------------
No comments:
Post a Comment