0

Why doesn't a static block in the class get executed when I don't create a reference variable for an object (anonymous) of that class?

For example, let us consider this simple class:

public class StaticDemo {

    private static int x;

    public static void display(){
        System.out.println("Static Method: x = "+x);
    }

    static {
        System.out.println("Static Block inside class");
    }

    public StaticDemo(){
        System.out.println("Object created.");
    }

}

Another class using it:

public class UseStaticDemo {
    public static void main(String[] args) {
        StaticDemo Obj = new StaticDemo();
        Obj.display();

        System.out.println("------------");

        new StaticDemo().display();
    }
}

Output:

Static Block inside class
Object created.
Static Method: x = 0
------------
Object created.
Static Method: x = 0
5
  • Please read a bit about static blocks if you haven't done so already. Also, try to run the same code, but replace the anon object with a referenced one. Then, it will become clear. The answer lies in your code itself. Commented Oct 12, 2014 at 5:34
  • @BoratSagdiyev As indicated by the below answer, an object being referenced or anonymous has nothing to do with the static block being executed. It will be executed once whenever the class is first loaded. Commented Oct 12, 2014 at 6:15
  • 1
    That is exactly my point. Your output would be the same even if you used a non-anon object. So, you can get the answer yourself, without having to ask here. But, always feel welcome to ask. Commented Oct 12, 2014 at 6:20
  • @BoratSagdiyev I feel like an idiot now. I should have tried it before posting this question. :-( Commented Oct 12, 2014 at 6:22
  • 1
    No, you don't have to feel like an idiot. I did not mean to say that. Most of us are learners and I am too. So, its okay. Point is, you should relax and try as much as you can yourself. Then, come here. Don't doubt yourself too much and don't be too harsh on yourself. Cheer up and keep coding. Chenqui. Commented Oct 12, 2014 at 6:24

1 Answer 1

5

A static initializer block only runs once, when the class is loaded and initialized.

Also, static methods have absolutely no relation to any instances. Doing

new StaticDemo().display();

is pointless and unclear.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes you are write. The static block will only be executed once. By keeping only "new StaticDemo().display();" in the code, the static block did get executed. My bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.