I am wondering what’s the purposes of using empty block. For example,
static{
int x = 5;
}
public static void main (String [] args){
int i = 10;
{
int j = 0 ;
System.out.println(x); // compiler error : can't find x ?? why ??
System.out.println(i); // this is fine
}
System.out.println(j); //compiler error : can't find j
}
Can someone explains
- In what situation that we would want to use empty block.
- Are all the variables inside that empty block still goes on
stack? - Why couldn’t it access the
static variable x?
xbecause you did not declare it. Instead, you declared a local variablexinside a static initializer.If you would like to make
xa static variable and then initialize it in a static initialization block, do this:In trivial cases like this, a straightforward initialization syntax works best:
Initializer blocks are reserved for more complex work, for example, when you need to initialize structures using a loop: