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
stack
? static variable x
? A block of code may exist on its own or it can belong to an if , while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope.
Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.)
The built-in try function does not create its own scope. Modules, classes, and functions create scope.
Java method scope. A variable declared inside a method has a method scope. The scope of a name is the region of program within which it is possible to refer to the entity declared by the name without the qualification of the name. A variable which is declared inside a method has a method scope.
x
because you did not declare it. Instead, you declared a local variable x
inside a static initializer.If you would like to make x
a static variable and then initialize it in a static initialization block, do this:
private static int x;
static {
x = 5;
}
In trivial cases like this, a straightforward initialization syntax works best:
private static int x = 5;
Initializer blocks are reserved for more complex work, for example, when you need to initialize structures using a loop:
private static List<List<String>> x = new ArrayList<List<String>>();
static {
for (int i = 0 ; i != 10 ; i++) {
x.add(new ArrayList<String>(20));
}
}
Static blocks are useful to initialize static members since they run at class initialization time.
static final Map<K, V> MY_MAP = ...;
static {
MY_MAP.put(...);
...
}
Do all the variables inside that empty block still goes on stack ?
Variables declared in the static block are local variables, not static members of the class. As @veer points out, whether it goes on the stack is a VM implementation detail.
Why couldn't
main
access the static variablex
?
Because it's a local variable that only exists for the duration of the static
initializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With