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.
xis 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 useApp.x.