Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Sunday

static blocks in java

static blocks in java

static blocks are executed before the constructor is executed. The static block is executed only one, during the initialization of object or access the static member of that class for the first time.

public final class Test {


static int i;
    int j;
   
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
    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:
static block called 
10

public final class Test {


static int i;
    int j;
    Test(){
        System.out.println("Constructor called");
    }
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
    public static void main(String args[]) {
   
    Test t1 = new Test();
    }
}



Output:
static block called
Constructor called

No comments:

Post a Comment