What is a static block in Java ??
Points To Remember
- A static block is called only once and is not a member of a class.
- A static block is executed before execution of any other method in the class.
- If there are more than one static block in a class then, they are executed in order of their occurence in a class.
- They do not have a return statement.
- They cannot contain this or super reference.
What is a Static block in Java??
A static block is a block of code that gets executed first at the time the class is called or its object is created. Even if we have a main method in a class and we run this class, even then the code in the static block will be executed before the execution of the main method. If we have more than one static blocks in a clss then they gets executed in the same order as they appear in the code but before any method or even constructor gets executed. Also a static block is not a member of a class and does not contain any return statement or a this or super reference.
Example 1 - Static block executes before main() method.
public class HelloWorld{ static int test = 100; static{ test = 75; System.out.println("static1 test = " + test); } public static void main(String args[]){ test = 25; System.out.println("main() test = " + test); } static{ test = 50; System.out.println("static2 test = " + test); } }Output of the above program :
static1 test = 75
static2 test = 50
main() test = 25
Thus this clearly shows that the 1st staic block gets executed followed by 2nd and 3rd static blocks and after that main method gets executed.
Example 2 - Static block executes before constructor.
class Test{ public Test(){ System.out.println("Constructor"); } static{ System.out.println("static show of Test "); } } public class TestStatic{ static int test = 100; public static void main(String args[]){ Test obj = new Test(); System.out.println("main test = " + test); } static{ System.out.println("static show test = " + test); } }Output of the above program :
static show test = 100
static show of Test
Constructor
main test = 100
Thus this shows that, the static block of the class is called first, then the method main is executed, when object of class Test is made, first the static block of the class is executed and then the constructor is called. Thus static block gets executed before the constructor is executed.
No comments: