1

The result is:

1
3
1
3
1
3
2

The constructor runs for A,B and for C (3 times). But if you use static keyword it runs only once. What is the reason of this? And why does this line executes last?

enum Enums {
    A, B, C;

    {
        System.out.println(1);
    }

    static {
        System.out.println(2);
    }

    private Enums() {
        System.out.println(3);
    }
}

public class MainClass{
    public static void main(String[] args) {
        Enum en = Enums.C;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
lipilocid
  • 87
  • 8
  • What is your understanding of the meaning of `static` in Java? – khelwood Jul 31 '18 at 15:03
  • 1
    Your question is very strangely worded. "But if you use static keyword it runs only once" _it_ here seems to refer to the constructor, but the constructor is still executed three times. It's just the static block that's executed just once. – tobias_k Jul 31 '18 at 15:06

2 Answers2

1

There are three different things at play here:

private Enums()
{
    System.out.println(3);
}

This is the constructor. It (or some other potential constructor) runs when an instance is created.

{
    System.out.println(1);
}

This is an instance initializer. It runs when an object is being constructed, regardless of which constructor is used.

static
{
    System.out.println(2);
}

This is a static initializer. It gets run once this class has been loaded into the JVM, whether or not an instance is being created. However, since we're dealing with an enum, all its instances have to be created as part of loading the class. That's why it runs after the three constructors and initializers.

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
1

To complement @smallhacker answer you should read the answers in Static initializer in Java

Uff! what is static initializer?

The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.