0

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.
      }             
}

         

Thank you.

1
  • 2
    It's not a matter of precedence, it's a matter of scope. The second x is declared locally and is only visible in the scope of the static block, just like any static method. To access the outer variable within the block, you can use App.x. Commented Dec 3, 2017 at 23:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.