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
UrsinusTheStrong
  • 1,239
  • 1
  • 16
  • 33
  • 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. – Erran Morad Oct 12 '14 at 05: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. – UrsinusTheStrong Oct 12 '14 at 06: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. – Erran Morad Oct 12 '14 at 06:20
  • @BoratSagdiyev I feel like an idiot now. I should have tried it before posting this question. :-( – UrsinusTheStrong Oct 12 '14 at 06: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. – Erran Morad Oct 12 '14 at 06:24

1 Answers1

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.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 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. – UrsinusTheStrong Oct 12 '14 at 05:58