The code 1:
public class StaticBlockExample1
{
static { value = 20; }
static int value = 10;
public static void main(String[] args) {
System.out.println(" Value = " + value);
}
}
output of StaticBlockExample1 is 10
The code 2:
public class StaticBlockExample2
{
static int value = 10;
static { value = 20; }
public static void main(String[] args)
{
System.out.println(" Value = " + value);
}
}
output of StaticBlockExample2 is 20.
Am confused with outputs of the above examples. is there any significance to declare static variable before or after static block?
是的,静态块和静态字段初始化按照在输入文件中找到它们的顺序执行。
The most important is order of your inicializations. - 1st case - 10 is defined as second
static int value = 10;
and in 2nd case , block is second
static {
value = 20;
}
order of initialization is different
first: you define static block before variable declaration
second: you define static block after variable declaration
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.