Search code examples
javastatic-variables

Static variables and instance block in Java


When initializing an instance variable in a static block, it's throwing compilation error (so only static variables are declared in static block). However, my program is executing without any problem when I'm initializing static variable in an instance initializer block. So, is it OK to initialize static variable in instance block?


Solution

  • It's possible to do this, but usually not desirable. The instance initializer block will run whenever a new instance is created, and overwrite any existing value in the static fields.