Q:

Static block vs Static declaration in terms of variables [Java]

Below is a legal java program that runs fine and prints 5.
Can someone help me understand what is going on with the variables in the static block. Why can x be legally declared twice? Does the static declaration take precedence over the static block?
Does the static block variable 'x' shadow the static variable 'x' declared on the top of this small program. If so how is it accessed?
public class App{

  static int x = 2;
  static int z;

  static{
    int x = 3;
    z = x;
  }

  public static void main(String args[]){   
    System.out.println(x+z); //Output is 5.
  }             

}             
Thankyou.

A:

The x in the static block is a local variable of the static block and it shadows the static int x. It is not another declaration of the static variable x - it is a declaration of a local variable x inside the static block. In order to access the outer x, you can reference it with App.x inside the static block, just as you can elsewhere.
The behaviour is no different than declaring a local variable in the constructor of a class:
public class App {
  int i = 0;
  int j;

  public App() {
    int i = 2; // This i is a local variable in the constructor
    j = i;
  }
}

The i in the constructor is a local variable and it shadows this.i, but once the constructor is executed, the local i is lost, and this.i stays 0 as originally declared.
The static block works analogously. You can think of it kind of like a static constructor, a constructor of the class, as opposed to the "normal" constructor which constructs instances (objects) of a class.

