-2

Why can't we initialize a static variable in an anonymous block in java? For eg : Why doesn't this code compile?

public class A {
  {
      static int a = 1;
  }
}

I get this compile error saying

Illegal modifier for the variable a; only final is permitted

Why only final?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • such you're trying not just to *initialize*, but also to *declare*, which is not allowed for static members there. – Alex Salauyou Mar 31 '16 at 11:13
  • 1
    What would you expect it to do? Variables declared inside instance initializers are local variables, and you can't make a local variable static... – Jon Skeet Mar 31 '16 at 11:15

4 Answers4

3

Directly within class, a block is an instance initializer block. You can't declare static variables in an instance initializer block. Simply remove it from the block:

public class A {
    static int a=1;
}

Instance initializer blocks are called when instances are created, prior to the code in any instance constructors. So it makes sense you can't declare members there (static or otherwise). They're code, as though inside a constructor. Example:

import java.util.Random;

public class Example {
    private String name;
    private int x;
    private int y;

    {                                     // This is the
        this.x = new Random().nextInt();  // instance
        this.y = this.x * 2;              // initializer
    }                                     // block

    public Example() {
        this.name = null;
    }

    public Example(String name) {
        this.name = name;
    }
}

In the above, regardless of which constructor is used, the first thing that happens is the code in the instance initializer block, followed by the code in the constructor that was used.

There are also static initializer blocks, which do the same thing for static stuff when the class is loaded. They start with the keyword static, more in the link above.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

From the docs of

Initialization blocks

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

The code you wrote will moved to constructor. A static member local to the constructor won't make much sense they must be declared at class level and not local to the constructor

And you are seeing in the error message only final is permitted, because you can modify the final variables in constructor if you haven't yet initialize them at the time of declaration.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1
{
      static int a=1;
}

you can't have static modifier in a code block , a here is just a local variable

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

you can do static field initialization in a static block. But not the declaration.

public class A{
  static int a;
  static
  {
    a = 1;
  }
}
tejoe
  • 163
  • 1
  • 14