Table of Contents

    Java static Block: Definition and Usage

    Java static Block: Definition and Usage

    Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). For example, check output of following Java program.

    Program
    // filename: MainClass.java
    class Test {
        static int i;
        int j;
    
        // start of static block
        static {
            i = 20;
            System.out.println("static block called ");
        }
        // end of static block
    }
    
    class MainClass {
        public static void main(String args[]) {
    
            // Although we don't have an object of Test, static block is
            // called because i is being accessed in following statement.
            System.out.println(Test.i);
        }
    }
    Output:
    show method of sub class.
    display method of super class.
    Press any key to continue . . .

    static blocks are executed before constructors.

    Also, static blocks are executed before constructors. For example, check output of following Java program.

    Program
    // filename: MainClass.java
    class Test {
        static int i;
        int j;
    
        // start of static block
        static {
            i = 20;
            System.out.println("static block called ");
        }
        // end of static block
    }
    
    class MainClass {
        public static void main(String args[]) {
    
            // Although we don't have an object of Test, static block is
            // called because i is being accessed in following statement.
            System.out.println(Test.i);
        }
    }
    Output:
    show method of sub class.
    display method of super class.
    Press any key to continue . . .